Re: Check for dict key existence, and modify it in one step.
- From: Bruno Desthuilliers <bruno.42.desthuilliers@xxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Tue, 28 Aug 2007 16:59:44 +0200
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
.
- Follow-Ups:
- References:
- Check for dict key existence, and modify it in one step.
- From: rodrigo
- Check for dict key existence, and modify it in one step.
- Prev by Date: Re: wxpython:how to minimize to taskbar
- Next by Date: Re: Python Classes
- Previous by thread: Check for dict key existence, and modify it in one step.
- Next by thread: Re: Check for dict key existence, and modify it in one step.
- Index(es):
Relevant Pages
|