The following three dictionaries are given:
The information has been extracted from a tree structure. The dictionaries show the parent-child relationship.
root
|
|_A
| |__C
| |
| |__D
| |
| |__E
| |
| |__F
|
|__B
dict1 = {"A":300, "B":200}
dict2 = {"A": {"C":100, "D":200}}
dict3 = {"D": {"E":100, "F":100}}
The result should look like this:
dict_result = {"C":100, "E":100, "F":100, "B":200}
"A" (key and value) in Dict1 should be replaced with the value from Dict2 with the key "A". The same should be applied for "D" in Dict2 with the specific value from Dict3. The order of the result should look like showed above in dict_result.
I tried some recursive stuff and with a try, I combined all the dicitonaries into one nested one, but I still can't find a solution
dict_nested = {"A":{"C":100, "D":{"E":100, "F":100}}, "B":200}
additional Information:
So, assuming all the rest of the dictionaries are similar in type to dict2 and dict3 (and only dict1 is different), you can use the following recursion:
from typing import List, Dict
def func(dct: Dict[str, int], rest: List[Dict[str, Dict[str, int]]]):
if not rest:
return dct
first = rest[0]
res = {}
for key, value in dct.items():
if key in first:
res.update(first[key])
else:
res[key] = value
return func(res, rest[1:])
And then, to use it in the following way:
dict1 = {"A":300, "B":200}
dict2 = {"A": {"C":100, "D":200}}
dict3 = {"D": {"E":100, "F":100}}
func(dict1, [dict2, dict3]) # {'C': 100, 'E': 100, 'F': 100, 'B': 200}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.