dictionary initialization

Berthold Höllmann bhoel at despammed.com
Thu Nov 25 17:02:09 EST 2004


wgshi at namao.cs.ualberta.ca (Weiguang Shi) writes:

> Hi,
>
> 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, I got
>     >>> b={}
>     >>> b[1] = b[1] +1
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in ?
>     KeyError: 1
>
> That is, I have to initialize b[1] explicitly in the first place.
>
> Personally, I think
>
>     a[i]++
>
> in awk is much more elegant than
>
>     if i in a: a[i] += 1
>     else: a[i] = 1
>
> I wonder how the latter is justified in Python.

It isn't :-)

>>> a={}
>>> a[1] = a.get(1, 0) + 1
>>> a
{1: 1}
>>> a[1] = a.get(1, 0) + 1
>>> a
{1: 2}

Regards
Berthold
-- 
berthold at xn--hllmanns-n4a.de / <http://höllmanns.de/>
bhoel at web.de                 / <http://starship.python.net/crew/bhoel/>



More information about the Python-list mailing list