defaultdict(None)

Python

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

In this use case, don't use defaultdict at all -- a plain dict will do just fine:

states = {}
if new_state_1 != states.get("State 1"):
    dispatch_transition()

The dict.get() method returns the value for a given key, or a default value if the key is not found. The default value defaults to None.

Solution 3 - Python

I guess I could also do this:

states = {}
...
if not new_state_1 in states or new_state_1 != states["State 1"]:
    dispatch_transition()

But I much prefer the defaultdict method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBazView Question on Stackoverflow
Solution 1 - PythonBjörn PollexView Answer on Stackoverflow
Solution 2 - PythonSven MarnachView Answer on Stackoverflow
Solution 3 - PythonBazView Answer on Stackoverflow