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

Steven D'Aprano steve at pearwood.info
Mon Jun 4 20:25:56 EDT 2018

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. 

Can you give some examples of when you want to do that? I'm having 
difficulty in thinking of any. The only example I thought of is when you 
have a "preferences" or "settings" dict, and you want to add default 
settings but only if the user hasn't provided them. But the way to do 
that is to go in the opposite direction, starting with the defaults, and 
unconditionally add user settings, overriding the default.

    # wrong way (yes, I've actually done this :-(
    settings = get_user_prefs()
    for key, value in get_default_prefs():
        if key not in settings:
            settings[key] = value

    # right way
    settings = get_default_prefs()

So I'm afraid I don't see the value of this.

> 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

Can you give an real-life example of the five line version?

> 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.

I don't see any connection between "append" and "fail if the key already 
exists". That's not what it means with lists.


More information about the Python-ideas mailing list