【发布时间】:2015-12-01 13:27:32
【问题描述】:
从Comparing/combining two dictionaries 开始,我正在尝试研究如何合并两个嵌套的 OrderedDicts。
我拥有的数据类似于这样的简化形式:
personA = OrderedDict([
(u'score',
OrderedDict([(u'2015-09-09 03:40:33 +0100', 2646),
(u'2015-09-10 03:35:34 +0100', 2646),
])
),
(u'adjusted_score',
OrderedDict([(u'2015-09-09 03:40:33 +0100', 3646),
(u'2015-09-10 03:35:34 +0100', 3646),
])
)
]
)
personB = OrderedDict([
(u'score',
OrderedDict([(u'2015-09-11 03:40:33 +0100', 4646),
(u'2015-09-12 03:35:34 +0100', 4646),
])
),
(u'adjusted_score',
OrderedDict([(u'2015-09-11 03:40:33 +0100', 5646),
(u'2015-09-12 03:35:34 +0100', 5646),
])
)
]
)
我想将'personA' 和'personB' 合并到一个新的output 变量中,键为personA(假设它们实际上是同一个人)。
到目前为止,我已经尝试过这段代码,但所有值都以列表形式结束。我不介意是否覆盖任何数据,但输出必须包含相同的数据结构:
output = collections.OrderedDict()
for k,e in personA.items()+personB.items():
output.setdefault(k,[]).append(e)
【问题讨论】:
标签: python dictionary merge ordereddictionary