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"]:

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?



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)

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"):

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.

I guess I could also do this:

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

But I much prefer the defaultdict method.