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

标签 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”,其值是“{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/

相关文章:

python - 基于增长率优化值的迭代计算

python - scrapy:错误:异常(exception)。AttributeError: 'Response'对象没有属性 'xpath'

python - 用 nltk 搜索相似的意思短语

python - 在python中更新字典

c++ - 如何在控制台上显示 map 的内容?

c# - Linq - 创建一个设置长度的列表,默认值为空

Python 和 mySQLdb 错误 : OperationalError: (1054, "Unknown column in ' where 子句'")

php - 合并两个关联数组而不重新索引 - PHP

sql-server - 对相同的源表和目标表使用 SQL Server MERGE 命令

python - 如何以Python方式从嵌套字典中获取键