setting the default string value of Python's collections.defaultdict

Question:

I am using Python 3.2.3 and want to change the default returned string value:

from collections import defaultdict
d=defaultdict(str)
d["NonExistent"]

The value returned is ''. How can I change this so that when a key is not found, "unknown" is returned instead of the empty string?

Asked By: jftuga

||

Answers:

The argument to defaultdict is a function (or rather, a callable object) that returns the default value. So you can pass in a lambda that returns your desired default.

>>> from collections import defaultdict
>>> d = defaultdict(lambda: 'My default')
>>> d['junk']
'My default'

Edited to explain lambda:

lambda is just a shorthand for defining a function without giving it a name. You could do the same with an explicit def:

>>> def myDefault():
...     return 'My default'
>>>> d = defaultdict(myDefault)
>>> d['junk']
'My default'

See the documentation for more info.

Answered By: BrenBarn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.