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

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


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.