[英]How to add the values of two OrderedDict objects in python, keeping the order?
I would like to add two OrderedDict
objects like these: 我想添加两个这样的
OrderedDict
对象:
dict1 = OrderedDict([('Table', [10, 20, 30, 'wood']), ('Chair', [200, 300, 400, 'wood'])])
dict2 = OrderedDict([('Table', ['red', 55]), ('Chair', ['blue', 200])])
And create a new OrderedDict
like this (the order is important): 并像这样创建一个新的
OrderedDict
(顺序很重要):
dict3 = OrderedDict([('Table', [10, 20, 30, 'wood', 'red', 55]), ('Chair', [200, 300, 400, 'wood', 'blue', 200])])
If there are any keys in dict1
or dict2
that are not present in the other, those should be ignored, only matching keys should be used for the output. 如果
dict1
或dict2
中的其他键不存在,则应将其忽略,仅将匹配的键用于输出。 All values are lists. 所有值都是列表。
Because you want to preserve the order of your OrderedDict
objects, you need to loop over one and test each key against the other to produce the union of the two key sets: 因为您要保留
OrderedDict
对象的顺序,所以需要循环一个并针对每个键测试每个键以产生两个键集的并集:
dict3 = OrderedDict((k, dict1[k] + dict2[k]) for k in dict1 if k in dict2)
Looping over dict1
ensures that we output keys for the new dictionary in the same order, testing with k in dict2
ensures we only use keys that are present in both input mappings. 循环
dict1
可以确保我们以相同的顺序输出新字典的键, k in dict2
中用k in dict2
可以确保我们仅使用两个输入映射中都存在的键。
You can also update dict1
in-place with list.extend()
: 您也可以使用
list.extend()
就地更新dict1
:
for key, value in dict1.items():
if key in dict2:
value.extend(dict2[key])
Demo: 演示:
>>> 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])])
dict3 = {}
for i in dict1:
if i in dict2:
dict3[i]=[]
for j in dict1[i]:
dict3[i].append(j)
for j in dict2[i]:
dict3[i].append(j)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.