本文介绍了如何在同一词典下合并两个嵌套词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有一本字典:
dictA={"nest1":{"01feb":[1,2,3,4,5],"02feb":[1,7,8,9,10]},
"nest2":{"01feb":[1,2,3,4,5],"02feb":[6,4,8,10,10]}}
里面的列表具有相同的长度.我需要将 nest1 和 nest2 合并为一个字典,其结果应如下所示:
the list inside has the same length. I need to merge nest1 and nest2 as one dictionary, and the result should be like this:
dictA={"nest":{"01feb":[2,4,6,8,10],"02feb":[7,11,16,19,20]}}
推荐答案
请为您的查询找到以下代码.
Plese find the below code for your query.
dictA={"nest1":{"01feb":[1,2,3,4,5],"02feb":[1,7,8,9,10]},
"nest2":{"01feb":[1,2,3,4,5],"02feb":[6,4,8,10,10]}}
result ={}
final_op = {}
for k,v in dictA.iteritems():
for nk,nv in v.iteritems():
if result.has_key(nk):
i=0
while i < len(result[nk]):
result[nk][i] += nv[i]
i += 1
else:
result[nk] = nv
final_op['nest'] = result
print final_op
输出:
{'nest': {'02feb': [7, 11, 16, 19, 20], '01feb': [2, 4, 6, 8, 10]}}
这篇关于如何在同一词典下合并两个嵌套词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!