简体   繁体   中英

Is there a way to replace key-value pairs within a dictionary by specific values from another dictionary?

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:

  • Dict1 has already Information about "A". But there is some more specific information within other sources which we dont want to loose.
  • The order of every Dictionary is important and should not changed.
  • Dtypes of keys are always strings / Dtypes of values are either Integers or another dictionary (somtimes nested).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM