Append a new value to dict

Frank Niemeyer frank.niemeyer at uni-ulm.de
Wed Oct 22 10:48:25 EDT 2008


> 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



More information about the Python-list mailing list