【问题标题】:How to merge two dictionaries based on their keys and values in Python?如何根据 Python 中的键和值合并两个字典?
【发布时间】:2019-05-15 06:22:33
【问题描述】:

我在 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}}

【问题讨论】:

  • 是否可以将您的帖子编辑成有效的python?

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


【解决方案1】:

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}}

【讨论】:

  • 您好,我遇到以下错误:o['House'] = value['House'] TypeError: 'NoneType' object does not support item assignment
  • 该错误意味着 var o 是 None ,这很奇怪。如果您将代码复制到文件中并使用 python 运行它,您会收到该错误吗?
  • 这是我自己的一些小错误。之后一切正常。非常感谢!
猜你喜欢
  • 2021-09-17
  • 2021-12-28
  • 2022-11-28
  • 1970-01-01
  • 1970-01-01
  • 2022-12-12
  • 2016-04-17
  • 1970-01-01
  • 2016-02-22
相关资源
最近更新 更多