dictionary initialization

Weiguang Shi wgshi at namao.cs.ualberta.ca
Thu Nov 25 13:38:17 EST 2004


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.

Thanks,
Weiguang



More information about the Python-list mailing list