Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defaultdict(None)

Tags:

python

I wish to have a dictionary which contains a set of state transitions. I presumed that I could do this using states = defaultdict(None), but its not working as I expected. For example:

states = defaultdict(None) if new_state_1 != states["State 1"]:     dispatch_transition() 

I would have thought that states["State 1"] would return the value None and that if new_state is a bool that I would have gotten False for new_state != states["State 1"], but instead I get a KeyError.

What am i doing wrong?

Thanks,

Barry

like image 528
Baz Avatar asked Oct 25 '11 08:10

Baz


People also ask

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 does Defaultdict mean?

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 Defaultdict list do in Python?

The Python defaultdict type behaves almost exactly like a regular Python dictionary, but if you try to access or modify a missing key, then defaultdict will automatically create the key and generate a default value for it. This makes defaultdict a valuable option for handling missing keys in dictionaries.

How do I get rid of Defaultdict?

Just use the same syntax as you would on a regular dictionary. del mydict['stock2'] for example, or mydict. pop('stock2') if you want the value returned at the same time. Note that you don't need to be using a defaultdict at all in your example.


1 Answers

defaultdict requires a callable as argument that provides the default-value when invoked without arguments. None is not callable. What you want is this:

defaultdict(lambda: None) 
like image 139
Björn Pollex Avatar answered Sep 20 '22 19:09

Björn Pollex