Append a new value to dict

Pat Pat at junk.net
Fri Oct 17 09:17:38 EDT 2008


paul wrote:
> Pat schrieb:
>> 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 ;
> Whats wrong with:
> 
> mytable[key] = value
> 
> cheers
>  Paul
> 

mytable[key] = value

is the code that I wound up using.   It's obvious now that I know the 
answer. Thank you very much to all for your help.

In a earlier question (I can't find the thread in my newsreader), I 
asked about an array of dict to dict and someone supplied me with the 
answer.

[state]={}
[state][city]={}
['Florida']['Tampa] = 20

It worked out perfectly and the Python code is a billion times easier to 
read than the Perl version.
Of all the languages I've learned and used professionally, I'm finding 
Python to be one of the best languages to learn and use.

Having Wing IDE Pro has made it a lot easier for me to learn and debug. 
    It does have a few bugs but they always respond by email within 
several hours.  Absolutely superb customer support. And no, I'm in no 
way affiliated with Wingware except that I'm a satisfied customer.



More information about the Python-list mailing list