dict.popitem(key) ???

Alex Martelli aleax at aleax.it
Sun Mar 16 08:15:29 CET 2003

Raymond Hettinger wrote:

> "Justin Shaw"
>> Why doesn't popitem take a key argument that defaults to None?  Or how
>> should I pop a particular item out of a dict?
> In Py2.3, dict.pop can take an optional default argument:
>    avalue =  mydict(possiblekey, default)
> It can also just search for a specified key and return an
> exception if not found:
>   avalue = mydict(possiblekey)

Just to clarify (I think a ".pop" just failed to appear here):

Python 2.3a2+ (#10, Mar 16 2003, 08:10:57)
[GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> ad=dict.fromkeys('ciao')
>>> ad
{'i': None, 'a': None, 'c': None, 'o': None}
>>> ad.pop('z')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 'z'
>>> ad.pop('z',23)
>>> ad.pop('a',23)
>>> ad
{'i': None, 'c': None, 'o': None}

If you can't use 2.3 (still in alpha stage), then as somebody else
suggested you can still do the job, albeit in two steps:

>>> ad.get('o',42)
>>> del ad['o']
>>> ad
{'i': None, 'c': None}


More information about the Python-list mailing list