Frank Niemeyer wrote:
>
>> However incrementing a non-existing key throws an exception.
>
> Right. And that's exactly what I would expect, according to the
> "principle of least surprise" Python tries to obey. There's simply no
> way to increment a non-existent value - not without performing some
> obscure implict behind-the-scenes stuff.
>
>> So you
>> either have to use a workaround:
>>
>> >>> try:
>> ... counter['B'] += 1
>> ... except KeyError:
>> ... counter['B'] = 1
>
> Or you could simply use
>
> if counter.has_key('B'):
> counter['B'] += 1
> else:
> counter['B'] = 1
>
> Regards,
> Frank
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
or
if 'B' in counter:
counter['B'] += 1
else:
ocunter['B'] = 1
--
View this message in context:
http://www.nabble.com/Append-a-new-value-to-dict-tp19953085p20127415.html
Sent from the Python - python-list mailing list archive at Nabble.com.
--
http://mail.python.org/mailman/listinfo/python-list