Tuesday, December 28, 2010

the confusingly named setdefault

setdefault has the same behavior as the following function:

>>> def setdefault2(my_dict, key, def):
...    my_dict[key] = my_dict.get(key, def)
...    return my_dict[key]
...
>>> a = {}
>>> setdefault2(a, "1", "2")
'2'
>>> a.setdefault(1, 2)
2
>>> setdefault2(a, "1", "3")
'2'
>>> a.setdefault(1, 3)
2
>>> a
{'1': '2', 1: 2}


This function is useful in similar cases to a collections.defaultdict.  The difference being, with this function you can choose what you want the default to be each time you fetch a key from the dictionary.  With a defaultdict, the default value for a missing key must be set at construction time.

No comments:

Post a Comment