defaultdict(None)

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


Solution 1:

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:

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.