简体   繁体   English

有没有办法用另一个字典中的特定值替换字典中的键值对?

[英]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". Dict1 中的“A”(键和值)应替换为带有键“A”的 Dict2 中的值。 The same should be applied for "D" in Dict2 with the specific value from Dict3.对于 Dict2 中的“D”,其具体值也应适用于 Dict3。 The order of the result should look like showed above in dict_result.结果的顺序应如上面 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". Dict1 已经有关于“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).键的 Dtypes 始终是字符串/值的 Dtypes 是整数或另一个字典(有时是嵌套的)。

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:所以,假设字典的所有 rest 在类型上都与 dict2 和 dict3 相似(只有 dict1 不同),可以使用以下递归:

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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