如何在Python中根据键和值合并两个字典?

时间:2018-12-14 00:26:33

标签: python dictionary merge compare key-value-store

我在基于Python的键和值合并两个字典时遇到问题。我有以下情况:

dictionary_1 = { 1{House: red, index=1} , 2{House: blue, index=2} , 3{House: green, index=3}}



dictionary_2 = { 4{Height: 3, index =3} , 5{Height: 5, index=1} , 6{Height: 6, index=2}

例如,在“ dictionary_1” 中,我有一个大型词典,其键是“ 1”,“ 2”和“ 3” ,及其值分别为“ {房屋:红色,索引= 1}”和“ {房屋:蓝色,索引= 2}”和“ {房屋:绿色,索引= 3}”。如您所见,大词典本身也是字典。相同的逻辑也适用于Dictionary_2。

我的目标是比较两个大字典的值:“ dictionary_1”和“ dictionary_2”。然后,如果两个字典的“索引”项具有相同的值,我想将它们合并在一起,而不必复制“索引”项。

因此输出应类似于:

dictionary_output = { 1{House: red, index=1, Height:5} , 2{House: blue, index=2, Height:6} , 3{House: green, index=3, Height: 3}}

1 个答案:

答案 0 :(得分:0)

setdefault是您遇到此类问题的朋友

dictionary_1 = { 1: { "House": "red", "index": 1},
                 2: { "House": "blue", "index": 2},
                 3: { "House": "green", "index": 3}}

dictionary_2 = { 4: { "Height": 3, "index": 3},
                 5: { "Height": 5, "index": 1},
                 6: { "Height": 6, "index": 6}}

output = {}

for k, v in dictionary_1.items():
    o = output.setdefault(v.get("index"), {})
    o['House'] = v['House']
    o['index'] = v['index']

for k, v in dictionary_2.items():
    o = output.setdefault(v.get("index"), {})
    o['Height'] = v['Height']
print(output)

将产生:

{1: {'House': 'red', 'Height': 5, 'index': 1}, 2: {'House': 'blue', 'index': 2}, 3: {'House': 'green', 'Height': 3, 'index': 3}, 6: {'Height': 6}}