Append a new value to dict

Mathias Frey mette.lemur at wu-wien.ac.at
Mon Oct 13 08:10:43 EDT 2008


Pat wrote:
> I know it's not "fair" to compare language features, but it seems to me 
> (a Python newbie) that appending a new key/value to a dict in Python is 
> awfully cumbersome.
> 
> In Python, this is the best code I could come up with for adding a new 
> key, value to a dict
> 
> mytable.setdefault( k, [] ).append( v )
> 
> In Perl, the code looks like this:
> 
> $h{ $key } = $value ;

There's a huge difference here:

In your Python example you're using a list. In the Perl example you're 
using a scalar value.


> Is there a better/easier way to code this in Python than the 
> obtuse/arcane setdefault code?

When just assigning a new key-value-pair there's no problem in Python. 
(Just refer to the answers before.) When I switched from Perl to Python 
however I commonly ran into this problem:

 >>> counter = {}
 >>> counter['A'] = 1
 >>> counter['A'] += 1
 >>> counter['A']
2

Ok - assigning a key-value-pair works fine. Incrementing works as well.

 >>> counter['B'] += 1
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
KeyError: 'B'

However incrementing a non-existing key throws an exception. So you 
either have to use a workaround:

 >>> try:
...   counter['B'] += 1
... except KeyError:
...   counter['B'] = 1

Since this looks ugly somebody invented the setdefault method:

 >>> counter['B'] = counter.setdefault('B',0) + 1

And this works with lists/arrays as well. When there's no list yet 
setdefault will create an empty list and append the first value. 
Otherwise it will just append.

Greetings from Vienna,
mathias



More information about the Python-list mailing list