Home > OS >  Python defaultdict returns None on get, despite being initialized with a default value
Python defaultdict returns None on get, despite being initialized with a default value

Time:05-15

I am trying to code a variant of Dijkstra's shortest path algorithm. In doing that, I want to initialize the shortest path distances to math.inf, and have this value returned for any unseen key.

I am using a defaultdict, initialized as defaultdict(lambda:math.inf) with the hope of having an infinite value returned for a new key.

However, I am seeing None values being returned in the below example.

Initialization:

shortest_paths = defaultdict(lambda:math.inf)
shortest_paths[k] = 0

print(f"Initial values for shortest_paths = {shortest_paths}")

This prints:

Initial values for shortest_paths = defaultdict(<function Solution.networkDelayTime.<locals>.<lambda> at 0x1044818b0>, {2: 0})

Call:

print(f"n={n} and shortest_paths.get(n) = {shortest_paths.get(n)}")

This prints:

n=1 and shortest_paths.get(n) = None

This eventually leads to a comparison between the None object and an integer value, breaking my code.

shortest_paths[n] = min(shortest_paths.get(n), shortest_paths.get(current)   dist)

Leading to:

TypeError: '<' not supported between instances of 'int' and 'NoneType'

What I am trying to figure out is how is the value of the defaultdict not getting initialized.

This exact code pasted on the REPL is working fine. I am using VSCode, if that's relevant.

CodePudding user response:

the point of defaultdict is you use bracketed access always -- .get(...) retains its original semantics (inherited from dict):

>>> shortest_paths = defaultdict(lambda:math.inf)
>>> shortest_paths[5]
inf
>>> shortest_paths.get(5)
inf
>>> print(shortest_paths.get(6))
None
  • Related