dictionary initialization
Jeffrey Froman
jeffrey at fro.man
Thu Nov 25 19:00:57 EST 2004
Weiguang Shi wrote:
> With awk, I can do something like
> $ echo 'hello' |awk '{a[$1]++}END{for(i in a)print i, a[i]}'
>
> That is, a['hello'] was not there but allocated and initialized to
> zero upon reference.
>
> With Python ... <snip>
> I have to initialize b[1] explicitly in the first place.
You could use the dictionary's setdefault method, if your value is mutable:
>>> b={}
>>> for n in xrange(100):
... b.setdefault('foo', [0])[0] += 1
...
>>> b['foo'][0]
100
Jeffrey
More information about the Python-list
mailing list