43

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?

jftuga
  • 1,913
  • 5
  • 26
  • 49

1 Answers1

67

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.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384