dictionary initialization

Caleb Hattingh caleb1 at telkomsa.net
Thu Nov 25 21:12:18 EST 2004


Hmm :)

"b[1]" looks like a List (but you created a Dict)
"b['1'] looks more like a Dict (but this is not what you used).

If lists are your thing:

>>>  a = []
>>> a.append(1)
>>> a
[1]
>>> a[0] += 1
>>> a
[2]

If dicts are your thing:

>>> b = {}
>>> b['1'] = 1
>>> b
{'1': 1}
>>> b['1'] += 1
>>> b
{'1': 2}

Lists are ordered, Dicts are not.
Dict entries accessed with 'string' keys, List entries accessed with a  
position integer.

Which feature specifically do you want justification for?

thx
Caleb





> 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