I have a simple nested dict to indicate a graph with nodes, vertices, and edge weights in the form dict:
{node: {vertex: weight, ... } ...}.
Here is how I create it:
with open(file) as f:
__, __1 = next(f).split()
for line in f:
tail, head, weight = line.split()
g1[tail] = {}
g1[tail][head] = int(weight)
This code gives me the dict I want. However, when I run more code that creates a similar nested dict as well as accesses this dict, I run into an error. Here is the code:
nodes = g1.keys()
distance = {}
for n in nodes:
distance[n] = {}
for k in nodes:
distance[n][k] = graph[n][k]
Somewhere in here, this error crops up:
distance[n][k] = graph[n][k]
KeyError: '344'
indicating that I haven’t yet created a key for ‘344,’ which is what this code is trying to do. I thought by initializing each node n to a dict, I could then create an entry for distance[n][k]. I’ve tried using default dicts — the result is the same. Why?
After this
for-loopcompletes,nis equal to the last value innodes.There is no guarantee that for every
kinnodes,graph[n][k]exists:The
nodesare all tails, not heads. Sokis iterating over tails. Yetgraph[n][k]is placingkin the position expected for a head.The tails and the heads are not necessarily interchangeable, and the last tail,
n, may not be connected to every other tail,k.If you are trying to make
distancea copy ofgraph, then use