我在根据 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”,其值是“{House:red,index = 1}”和“{House:blue,index = 2}”和“{House:green,index = 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}}
最佳答案
setdefault 是解决此类问题的好 helper
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}}
关于python - 如何在Python中根据键和值合并两个字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53771950/