如何根据 Python 中的键和值合并两个字典?
How to merge two dictionaries based on their keys and values in Python?
我在根据其键和值合并 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”。 =24=],其值为“{House: red, index=1}”和“{House: blue, index=2}”和“{House: green, index=3}”。 如您所见,大字典的值也是字典本身。同样的逻辑也适用于 dictionary_2.
我的目标是比较两个大词典的值:"dictionary_1" 和 "dictionary_2"。然后,如果两个词典的 "Index" 项具有相同的值,我想将它们合并在一起,而不复制 "index" 项。
因此输出应该是这样的:
dictionary_output = { 1{House: red, index=1, Height:5} , 2{House: blue, index=2, Height:6} , 3{House: green, index=3, Height: 3}}
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}}
我在根据其键和值合并 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”。 =24=],其值为“{House: red, index=1}”和“{House: blue, index=2}”和“{House: green, index=3}”。 如您所见,大字典的值也是字典本身。同样的逻辑也适用于 dictionary_2.
我的目标是比较两个大词典的值:"dictionary_1" 和 "dictionary_2"。然后,如果两个词典的 "Index" 项具有相同的值,我想将它们合并在一起,而不复制 "index" 项。
因此输出应该是这样的:
dictionary_output = { 1{House: red, index=1, Height:5} , 2{House: blue, index=2, Height:6} , 3{House: green, index=3, Height: 3}}
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}}