Append a new value to dict

chemila66@hotmail.com chemila at 163.com
Thu Oct 23 05:22:25 EDT 2008




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.




More information about the Python-list mailing list