Check for dict key existence, and modify it in one step.

Jason tenax.raccoon at gmail.com
Tue Aug 28 11:27:14 EDT 2007


On Aug 28, 8:36 am, rodrigo <rodrigo... at gmail.com> wrote:
> Im using this construct a lot:
>
> if dict.has_key(whatever):
>     dict[whatever] += delta
> else:
>     dict[whatever] = 1
>
> sometimes even nested:
>
> if dict.has_key(whatever):
>     if dict[whatever].has_key(someother):
>         dict[whatever][someother] += delta
>     else:
>         dict[whatever][someother] = 1
> else:
>     dict[whatever]={}
>     dict[whatever][someother] = 1
>
> there must be a more compact, readable and less redundant way to do
> this, no?
>
> Thanks,
>
> Rodrigo

As Bruno said, don't shadow the built-in objects.  When things
inevitably go south because the dict class has been replaced by your
dictionary, it will be difficult for you to find out what went wrong.

Under Python 2.5, you have the defaultdict class in the collections
module [1].  (This class is trivial to implement in prior versions of
Python, too.)

>>> from collections import defaultdict
>>> myDict = defaultdict(lambda: 1)
>>> myDict['spam'] = 5
>>> myDict['spam'] += 10
>>> myDict['vikings'] += 20
>>> myDict
defaultdict(<function <lambda> at 0x00AAC970>, {'vikings': 21, 'spam':
15})
>>>

  --Jason

[1] The module documentation is at "http://docs.python.org/lib/module-
collections.html"




More information about the Python-list mailing list