[Tutor] setdefault method
Kent Johnson
kent37 at tds.net
Tue Mar 28 03:23:59 CEST 2006
Carroll, Barry wrote:
> Greetings:
>
> What is the purpose of the dictionary method setdefault(k[, x])?
setdefault() is perhaps badly named, but it is very useful. It doesn't
do what you think it does! From the docs:
setdefault() is like get(), except that if k is missing, x is both
returned and inserted into the dictionary as the value of k. x defaults
to None.
You could define your own like this (with an extra arg for the dict):
def setdefault(d, k, x=None):
if k in d:
return d[k]
else:
d[k] = x
return x
If k is in d, the existing value d[k] is returned. If k is not in d, the
magic happens - d[k] is set to x, and x is returned to you.
I find this most often useful when I want to make a dict that maps a key
to a list of values. For example I may have a list of key, value pairs
and I want to accumulate the list of all values for each key. This comes
up pretty often in my experience. Here is how to code it with setdefault():
d = {}
for k, v in some_list:
d.setdefault(k, []).append(v)
Here setdefault() will return the list that k maps to, if any, or
otherwise start a new list. In either case, you can append the new value
to the returned list and get the effect you want.
> And, if d.setdefault does not actually assign a default value for d, is there a way to do this?
See this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/389639
Kent
More information about the Tutor
mailing list