合并两本词典与嵌套数组 [英] Merging two dictionaries with nested arrays

查看:142
本文介绍了合并两本词典与嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字典

a = {'I': [1,2], 'II': [1,2], 'III': [1,2]}
b = {'I': [3,4], 'II': [3,4], 'IV': [3,4]}

如何合并它们,这样我得到以下结果。

how can i merge them such that i get the following result

c = merge_dicts(a,b)

其中c为 {'我':[1,2,3,4],'二':[1,2,3,4],'三':[1,2] 四:[3,4]}

是否有这样做的一个很好的Python的方式?

Is there a good pythonic way of doing this?

请注意,我是一个新手蟒蛇,虽然我使用Python的一样的话。
先谢谢了。

Note that I am a python newbie, even though I am using words like pythonic. Thanks in advance.

推荐答案

如果你需要的所有值:

from itertools import chain
from collections import defaultdict

a = {'I': [1,2], 'II': [1,2], 'IV': [1,2]}
b = {'I': [3,4], 'II': [3,4], 'V': [3,4]}

d = defaultdict(list)
for key, value in chain(a.iteritems(), b.iteritems()):
    d[key].extend(value)
d

输出:

defaultdict(<type 'list'>, {'I': [1, 2, 3, 4], 'II': [1, 2, 3, 4], 'V': [3, 4], 'IV': [1, 2]})

这篇关于合并两本词典与嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆