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



rodrigo a écrit :
Im using this construct a lot:

if dict.has_key(whatever):

<ot>
Avoid using builtin names as identifiers (it shadows the builtin name).
</ot>

Unless you're using an old Python version, you'd be better using
if whatever in my_dict:
# do something here

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?

There are other ways, yes. With Python <= 2.4.x, you can use dict.setdefault, with Python 2.5.x you can use a defaultdict (cf http://docs.python.org/whatsnew/modules.html).

HTH
.



Relevant Pages

  • Thoughts about Python
    ... learning Python. ... In order to create a static method we have to use a the builtin ... There is no need for the builtin... ... "Throwing away" this builtins would flatten the alreay flat learning ...
    (comp.lang.python)
  • Re: xml.doms weirdness?
    ... I run python as: ... After those imports is the standard Python traceback (because of the ... # installing zipimport hook ... import zipimport # builtin ...
    (comp.lang.python)
  • Re: Built-in functions and keyword arguments
    ... While we're at it, you should avoid using builtin's names for identifiers - here, using 'object' as the arg name shadows the builtin 'object' class). ...
    (comp.lang.python)
  • Re: bad marshal data in site.py in fresh 2.5 install win
    ... I am now on a different computer, one that has never heard of Python, ... import zipimport # builtin ... import _codecs # builtin ... import sys, encodings, encodings.aliases ...
    (comp.lang.python)
  • Re: Why are there no ordered dictionaries?
    ... ordered dictionaries are not needed when Python ... > 2.4 has the 'sorted' builtin. ... What does sortedhave anythng to do with orders like insertion order, ...
    (comp.lang.python)