Append a new value to dict

Pat Pat at junk.com
Mon Oct 13 07:30:07 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 ;
> 
> Is there a better/easier way to code this in Python than the 
> obtuse/arcane setdefault code?

Naturally, right after writing my post I found that there is an easier way:

table[ k ] = v

I found that in "Python for Dummies". How apropos.



More information about the Python-list mailing list