Add nested dictionaries

If you have a nested dictionary, where each "foreign" key can be displayed in a dictionary with several keys, how do you add a new key to the "internal" dictionary? For example, I have a list in which each element consists of three components: a foreign key, a domestic key, and a value (AB 10).

Here is the cycle that I still have

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

Right now, instead of adding a new key: value to the internal dictionary, any new key: value immediately replaces the internal dictionary.

For example, suppose keyList is just [(AB 10), (AD 15)]. The result of this cycle is

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

How can I make it instead

{'A' : {'B' : 10, 'D' : 15}}
+4
source share
1 answer

, dict e[0]. .

- :

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 " ". defaultdict.

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

Source: https://habr.com/ru/post/1655710/


All Articles