简体   繁体   English

合并两个 Python 字典时保留两个冲突的值

[英]Keeping Both Conflicting Values While Merging Two Python Dictionaries

I am trying to merge two dictionaries having similar keys with different values.我正在尝试合并两个具有不同值的相似键的字典。 Try to use dict01.update(dict02) function but it only returns the values of dict02 of similar keys.尝试使用dict01.update(dict02)函数,但它只返回相似键的dict02的值。

I want something like this我想要这样的东西

dict01 = {'a': 1, 'b': 2}
dict02 = {'b': 3, 'c': 4}

resultant_dict = {'a': 1, 'b': [2, 3], 'c': 4}

There is nothing built-in that can do that.没有任何内置的东西可以做到这一点。 But it is not that hard to build:但是构建起来并不难:

def smush(v1, v2):
    return [v1, v2] if v1 is not None and v2 is not None else v1 or v2

dict01 = {'a': 1, 'b': 2}
dict02 = {'b': 3, 'c': 4}
resultant_dict = {
    k: smush(dict01.get(k), dict02.get(k))
    for k in set(dict01) | set(dict02)
}

As Barmar rightly notes, this will require further checking down the road.正如 Barmar 正确指出的那样,这将需要进一步检查。 Making all values into lists is almost certainly better.将所有值放入列表几乎肯定会更好。 The only modification required is唯一需要修改的是

def smush(v1, v2):
    return [v1, v2] if v1 is not None and v2 is not None else [v1 or v2]

But since this now regularises the output format, the code can be generalised, which makes it much more compact:但由于这现在正则化了输出格式,代码可以通用化,这使得它更加紧凑:

dict01 = {'a': 1, 'b': 2}
dict02 = {'b': 3, 'c': 4}

def smush_dicts(*dicts):
    return {
      k: [d[k] for d in dicts if k in d]
      for k in set(k for d in dicts for k in d)
    }


print(smush_dicts(dict01, dict02))
# => {'b': [2, 3], 'c': [4], 'a': [1]}

EDIT: simpler and more correct.编辑:更简单,更正确。

dict01 = {'a': 1, 'b': 2}
dict02 = {'b': 3, 'c': 4}
resultant_dict = {}
for i in dict01:
    for j in dict02:
        if i == j:
            resultant_dict.update({i:[dict01.get(i),dict02.get(j)]})
            break
        else:
            resultant_dict.update({i:dict01.get(i)})

            
for i in dict02:
    if i not in resultant_dict:
        resultant_dict.update({i:dict02.get(i)})

print( resultant_dict)

Long but works well很长但效果很好

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

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