Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 776
jftuga Avatar asked Jun 06 '12 22:06

jftuga


People also ask

What is the default value in Defaultdict?

When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.

What is Defaultdict in collections Python?

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.

What does the Defaultdict () function do?

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.

What is collections Defaultdict INT?

defaultdict means that if a key is not found in the dictionary, then instead of a KeyError being thrown, a new entry is created.


1 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.

like image 166
BrenBarn Avatar answered Sep 23 '22 03:09

BrenBarn