Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}}
like image 991
Bob Avatar asked Sep 24 '16 19:09

Bob


1 Answers

You told your code to assign newly created dict to key e[0]. It's always replaced blindly and it 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 conditional is required to handle 'first key' case. Alternatively defaultdict can be used.

from collections import defaultdict
nested_dict = defaultdict(dict)
for e in keyList:
    nested_dict[e[0]].update({e[2] : e[3:]})
like image 171
Łukasz Rogalski Avatar answered Sep 26 '22 06:09

Łukasz Rogalski