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