在Python中合并列表的两个字典 [英] To merge two dictionaries of list in Python
本文介绍了在Python中合并列表的两个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有两个字典
x={1:['a','b','c']}
y={1:['d','e','f'],2:['g']}
我想要另一个字典z,它是x和y中的一个合并的
I want another dictionary z which is a merged one of x and y such that
z = {1:['a','b','c','d','e','f'],2:['g']}
是否可以执行此操作? 我尝试了更新操作
Is it possible to do this operation? I tried update operation
x.update(y)
但这给了我以下结果
z= {1:['d','e','f'],2:['g']}
推荐答案
Counter()
can be used in this case:
>>> x={1:['a','b','c']}
>>> y={1:['d','e','f'],2:['g']}
>>> from collections import Counter
>>> Counter(x) + Counter(y)
Counter({2: ['g'], 1: ['a', 'b', 'c', 'd', 'e', 'f']})
如果需要的结果是字典.您可以使用以下内容:
If desired result is a dict. You can use the following:
z = dict(Counter(x) + Counter(y))
这篇关于在Python中合并列表的两个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文