Re: Check for dict key existence, and modify it in one step.
- From: Jason <tenax.raccoon@xxxxxxxxx>
- Date: Tue, 28 Aug 2007 08:27:14 -0700
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.)
defaultdict(<function <lambda> at 0x00AAC970>, {'vikings': 21, 'spam':from collections import defaultdict
myDict = defaultdict(lambda: 1)
myDict['spam'] = 5
myDict['spam'] += 10
myDict['vikings'] += 20
myDict
15})
--Jason
[1] The module documentation is at "http://docs.python.org/lib/module-
collections.html"
.
- 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: Asking all python programmers.
- Next by Date: in design time activeX properties
- Previous by thread: Re: 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
|