python - 如何在 python 中添加两个 OrderedDict 对象的值,保持顺序?

标签 python dictionary ordereddictionary

我想添加两个 OrderedDict 对象,如下所示:

dict1 = OrderedDict([('Table', [10, 20, 30, 'wood']), ('Chair', [200, 300, 400, 'wood'])])
dict2 = OrderedDict([('Table', ['red', 55]), ('Chair', ['blue', 200])])

然后像这样创建一个新的 OrderedDict(顺序很重要):

dict3 = OrderedDict([('Table', [10, 20, 30, 'wood', 'red', 55]), ('Chair', [200, 300, 400, 'wood', 'blue', 200])])

如果 dict1dict2 中有任何键在另一个中不存在,则应忽略这些键,仅应将匹配的键用于输出。所有值都是列表。

最佳答案

因为您想保留 OrderedDict 对象的顺序,所以您需要遍历一个对象并针对另一个键测试每个键以生成两个键集的并集:

dict3 = OrderedDict((k, dict1[k] + dict2[k]) for k in dict1 if k in dict2)

遍历 dict1 确保我们以相同顺序输出新字典的键,用 k in dict2 测试确保我们只使用存在于 两个输入映射。

您还可以使用 list.extend() 就地更新 dict1:

for key, value in dict1.items():
    if key in dict2:
        value.extend(dict2[key])

演示:

>>> from collections import OrderedDict
>>> dict1 = OrderedDict([('Table', [10, 20, 30, 'wood']), ('Chair', [200, 300, 400, 'wood'])])
>>> dict2 = OrderedDict([('Table', ['red', 55]), ('Chair', ['blue', 200])])
>>> OrderedDict((k, dict1[k] + dict2[k]) for k in dict1 if k in dict2)
OrderedDict([('Table', [10, 20, 30, 'wood', 'red', 55]), ('Chair', [200, 300, 400, 'wood', 'blue', 200])])

关于python - 如何在 python 中添加两个 OrderedDict 对象的值,保持顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534776/

相关文章:

python - 从 systemd 运行持久性 python 脚本?

python - 将大文本文件拆分为句子

function - Emacs 按键输入备忘单

Ansible - with_dict : dictionary - How to use variables defined in each dictionary which depends upon others

python - 如何在 for 循环中使用 vstack 以便将 csr_matrix 矩阵附加在一起

python - 支持大圆距离和多边形的快速 python GIS 库

python - 在 Python 中存储集合数据的最佳方式是什么?

python - 使用 Python 将字典打印到 CSV 文件

python - 数字的递归数字和,是否有更好的方法来编写这个函数?

python - 将字典与行值映射