[Python-ideas] Add dict.append and dict.extend

Ben Rudiak-Gould benrudiak at gmail.com
Mon Jun 4 17:22:29 EDT 2018


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. 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). If
I don't verify it, I may overwrite a dict entry and produce silently
wrong output.

The names `append` and `extend` make sense now that dicts are defined
to preserve insertion order: they try to append the new entries, and
if that can't be done because it would duplicate a key, they raise an
exception.

In case of error, `extend` should probably leave successfully appended
entries in the dict, since that's consistent with list.extend and
dict.update.

The same methods would also be useful on sets. Unfortunately, the
names make less sense.

-- Ben


More information about the Python-ideas mailing list