defaultdict(None)

Question:

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

Asked By: Baz

||

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)
Answered By: Björn Pollex

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.

Answered By: Baz

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.

Answered By: Sven Marnach
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.