Bob Bob - 4 months ago 44
Python Question

Append nested dictionaries

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).

Here's the loop I have so far

for e in keyList:
nested_dict[e[0]] = {e[2] : e[3:]}

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

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

{'A' : {'D' : 15}}

How can I make it so that instead it's

{'A' : {'B' : 10, 'D' : 15}}


You told your code to assign newly created dict to key e[0]. It's always replaced blindly, so i does not look at previously stored value.

Instead you need something like:

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

If is required to handle 'first key' case. Alternatively defaultdict may be used.

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