通过键合并的两个字典的值的并集 [英] Union of values of two dictionaries merged by key

查看:40
本文介绍了通过键合并的两个字典的值的并集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有两个字典:


I have two dictionaries:

d1 = {'a':('x','y'),'b':('k','l')}
d2 = {'a':('m','n'),'c':('p','r')}

我如何合并这两个字典以获得这样的结果:

How do I merge these two dictionaries to get such result:

d3 = {'a':('x','y','m','n'),'b':('k','l'),'c':('p','r')}

当字典的值是简单类型(如int或str)时,此方法有效:

This works when values of the dictionary are simple type like int or str:

d3 = dict([(i,a[i]+b[i]) for i in set(a.keys()+b.keys())])

但是我不知道如何将列表作为值来处理...

But I have no idea how deal with lists as values...

注意:我的问题与不同如何在一个表达式中合并两个Python字典?因为我不想更新值而是添加它们

Notice: my question is different to How to merge two Python dictionaries in a single expression? cause I don't want to update values but add them

推荐答案

关于变量名,您的问题有些混乱,但是我认为这可以满足您的要求:

Your question is a little bit mangled with respect to variable names, but I think this does what you want:

d3 = dict([(i,d1.get(i,())+d2.get(i,())) for i in set(d1.keys()+d2.keys())])
d3
{'a': ('x', 'y', 'm', 'n'), 'b': ('k', 'l'), 'c': ('p', 'r')}

请注意,您可以使用 + 添加(即扩展) list s和 tuples .

Note that you can add (ie extend) lists and tuples with +.

这篇关于通过键合并的两个字典的值的并集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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