dictionary initialization

Dan Perl danperl at rogers.com
Thu Nov 25 15:28:05 EST 2004


I don't know awk, so I don't know how your awk statement works.

Even when it comes to the python statements, I'm not sure exactly what the 
intentions of design intention were in this case, but I can see at least one 
justification.  Python being dynamically typed, b[1] can be of any type, so 
you have to initialize b[1] to give it a type and only then adding something 
to it makes sense.  Otherwise, the 'add' operation not being implemented for 
all types, 'b[1]+1' may not even be allowed.

You're saying that in awk a['hello'] is initialized to 0.  That would not be 
justified in python.  The type of b[1] is undetermined until initialization 
and I don't see why it should be an int by default.

Dan

"Weiguang Shi" <wgshi at namao.cs.ualberta.ca> wrote in message 
news:slrncqc9kq.hj3.wgshi at namao.cs.ualberta.ca...
> 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