Trouble With Nested Dicts
<p>I have a simple nested dict to indicate a graph with nodes, vertices, and edge weights in the form dict:</p>

<p><code>{node: {vertex: weight, ... } ...}</code>. </p>

<p>Here is how I create it:</p>

<pre><code>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)
</code></pre>

<p>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: </p>

<pre><code>nodes = g1.keys()
distance = {}

    for n in nodes:
        distance[n] = {}
    for k in nodes:
        distance[n][k] = graph[n][k]
</code></pre>

<p>Somewhere in here, this error crops up: </p>

<pre><code>distance[n][k] = graph[n][k]
KeyError: '344'
</code></pre>

<p>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? </p>
