dictionary initialization
Jeffrey Froman
jeffrey at fro.man
Thu Nov 25 19:00:57 EST 2004
More information about the Python-list mailing list
Thu Nov 25 19:00:57 EST 2004
- Previous message (by thread): dictionary initialization
- Next message (by thread): dictionary initialization
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Previous message (by thread): dictionary initialization
- Next message (by thread): dictionary initialization
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list