[Python-ideas] Add dict.append and dict.extend
MRAB
python at mrabarnett.plus.com
Mon Jun 4 20:59:37 EDT 2018
On 2018-06-05 01:25, Steven D'Aprano wrote:
> On Mon, Jun 04, 2018 at 02:22:29PM -0700, Ben Rudiak-Gould wrote:
>> I'd like to propose adding `append` and `extend` methods to dicts
>> which behave like `__setitem__` and `update` respectively, except that
>> they raise an exception (KeyError?) instead of overwriting preexisting
>> entries.
>>
>> Very often I expect that the key I'm adding to a dict isn't already in
>> it.
>
[snip]
>> If I want to verify that, I have to expand my single-line
>> assignment statement to 3-5 lines (depending on whether the dict and
>> key are expressions that I now need to assign to local variables).
>
> I'm sorry, I can't visualise how it would take you up to five lines to
> check and update a key. It shouldn't take more than two:
>
> if key not in d:
> d[key] = value
>
It shouldn't take more than one:
d.setdefault(key, value)
:-)
[snip]
More information about the Python-ideas
mailing list