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



On Aug 28, 8:36 am, rodrigo <rodrigo...@xxxxxxxxx> 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"

.



Relevant Pages

  • Re: why? __builtins__ key added from eval
    ... when you pass mydict, it is used as the global variables in the eval, ... Then, you passed a code to eval('...', mydict), sometimes you ... that's why python modified mydict as a side-effect. ... Or you could do "dictionary comprehension" that collects only names you ...
    (comp.lang.python)
  • Re: how can I clear a dictionary in python
    ... just point myDict to an empty dictionary again ... variables point to things in Python. ... If there aren't other objects pointing to ...
    (comp.lang.python)
  • Re: A completely silly question
    ... All those Python modules don't ... but if you're having trouble reading the module documentation, ... could elaborate on what's giving you trouble. ... don't know how to read it, you're going to have trouble with Python. ...
    (comp.lang.python)