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

Chris Barker chris.barker at noaa.gov
Tue Jun 5 12:44:59 EDT 2018

I think your proposal got a bit confused by the choice of names, and that
you were proposing two things, one of which I think already exists

So, I _think_ what you are proposing is that there be a method something

def exclusive_add(self, key, value):
    if key in self:
        raise KeyError("the key: {} already exists in this
    self[key] = value

Which would make sense if  that is a common use case, and you make a pretty
good case for that, with the analogy to UNIQUE in database tables.

I will point out that  the DB case is quite different, because python dicts
have a way to of spelling it that's really pretty straightforward,
performant and robust.

However, .setdefault() is essentially a replacement for:

if key in a_dict:
    value = a_dict(key)
    a_dict[key] = default_value
    value = default_value

or a similar try: except block:

    value = a_dict[key]
except KeyError:
    a_dict[key] = default_value
    value = default_value

And I'm glad it's there.

So - -if this is a fairly common use case, then maybe it's worth adding.

Note that this would be adding a new method to not just dict, but to the
entire mapping protocol (ABC) -- so maybe a heavier lift than you're


PS: making sure this is what you are suggesting:

In [*12*]: *class* *my_dict*(dict):

    ...:     *def* exclusive_add(self, key, value):

    ...:         *if* key *in* self:

    ...:             *raise* *KeyError*("the key: *{}* already exists in
this dict".format(key))

    ...:         self[key] = value


In [*13*]: d = my_dict()

In [*14*]: d.exclusive_add('this', 5)

In [*15*]: d.exclusive_add('that', 6)

In [*16*]: d.exclusive_add('this', 7)


KeyError                                  Traceback (most recent call last)

<ipython-input-16-b7600f2469fb> in <module>()

----> 1 d.exclusive_add('this', 7)

<ipython-input-12-5f1c0f0709c6> in exclusive_add(self, key, value)

*      2*     def exclusive_add(self, key, value):

*      3*         if key in self:

----> 4             raise KeyError("the key: {} already exists in this

*      5*         self[key] = value

*      6*

KeyError: 'the key: this already exists in this dict'


Christopher Barker, Ph.D.

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180605/6ee7d2f2/attachment-0001.html>

More information about the Python-ideas mailing list