How to update value in dictionary?
mblume
mblume at socha.net
Wed Aug 27 14:44:14 EDT 2008
Am Wed, 27 Aug 2008 15:45:13 +0200 schrieb Diez B. Roggisch:
>
>> dict.update({"a":1}) SETS the dict item "a" 's value to 1.
>>
>> i want to increase it by 1. isnt that possible in an easy way?
>> I should use a tuple for this?
>
>
> 1) Don't use dict as name for a dictionary, it shadows the type dict
>
> 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?
Curious
Martin
More information about the Python-list
mailing list