How to update value in dictionary?

Fredrik Lundh fredrik at pythonware.com
Wed Aug 27 21:01:02 CEST 2008


mblume wrote:

>> 2) setdefault is your friend
>>
>> d = {}
>> d['a'] = d.setdefault('a', 1) + 1
>>
> d['a'] = d.get('a', 1) + 1
> 
> seems to me a little better, as d['a'] doesn't get set twice, right?

setdefault is pronounced "get, and set if necessary".  it only updates 
the dictionary if the key isn't already there:

 >>> help({}.setdefault)
Help on built-in function setdefault:

setdefault(...)
     D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
	
(since setdefault is a method, the second argument is evaluated whether 
it's used or not, but that's true for your approach as well, and isn't 
much of a problem for a light-weight object like the integer 1.)

</F>




More information about the Python-list mailing list