Append nested dictionaries
<p>If you have a nested dictionary, where each 'outer' key can map to a dictionary with multiple keys, how do you add a new key to the 'inner' dictionary? For example, I have a list where each element is composed of 3 components: an outer key, an inner key, and a value (A B 10).</p>

<p>Here's the loop I have so far</p>

<pre><code>for e in keyList:
    nested_dict[e[0]] = {e[2] : e[3:]}
</code></pre>

<p>Right now, instead of adding the new key:value to the inner dictionary, any new key:value outright replaces the inner dictionary.</p>

<p>For instance, lets say the keyList is just [(A B 10), (A D 15)]. The result with that loop is </p>

<pre><code>{'A' : {'D' : 15}}
</code></pre>

<p>How can I make it so that instead it's</p>

<pre><code>{'A' : {'B' : 10, 'D' : 15}}
</code></pre>

<p>You told your code to assign newly created dict to key <code>e[0]</code>. It's always replaced blindly and it does not look at previously stored value.</p>

<p>Instead you need something like:</p>

<pre><code>for e in keyList:
    if e[0] not in nested_dict:
        nested_dict[e[0]] = {}
    nested_dict[e[0]].update({e[2] : e[3:]})
</code></pre>

<p><code>If</code> conditional is required to handle 'first key' case. Alternatively <code>defaultdict</code> can be used.</p>

<pre><code>from collections import defaultdict
nested_dict = defaultdict(dict)
for e in keyList:
    nested_dict[e[0]].update({e[2] : e[3:]})
</code></pre>

python dictionary