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?
When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.
Defaultdict is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionaries and defaultdict are almost same except for the fact that defaultdict never raises a KeyError.
A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
defaultdict means that if a key is not found in the dictionary, then instead of a KeyError being thrown, a new entry is created.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With