How to update value in dictionary?
MRAB
google at mrabarnett.plus.com
Thu Aug 28 12:57:17 EDT 2008
On Aug 27, 8:01 pm, Fredrik Lundh <fred... at pythonware.com> wrote:
> 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.)
>
Both
d['a'] = d.setdefault('a', 1) + 1
and
d['a'] = d.get('a', 1) + 1
will set d['a'] to 2 if 'a' isn't initially in d.
More information about the Python-list
mailing list