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

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Tue Aug 28 10:59:44 EDT 2007


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



More information about the Python-list mailing list