如何在python中加入2个字典列表? [英] How to join 2 lists of dicts in python?
本文介绍了如何在python中加入2个字典列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个这样的列表:
l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}]
l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}]
,我想获取列表 l3
,它是 l1
和 l2
的连接,其中'a'的值
和'b'
在 l1
和 l2
中都相等即
and I want to obtain a list l3
, which is a join of l1
and l2
where values of 'a'
and 'b'
are equal in both l1
and l2
i.e.
l3 = [{'a': 1, 'b: 2, 'c': 3, 'd': 4, 'e': 101}, {'a': 5, 'b: 6, 'c': 7, 'd': 8, 'e': 100}]
我该怎么做?
推荐答案
您应该将结果累积在字典中.您应该使用'a'和'b'的值来构成此字典的键
You should accumulate the results in a dictionary. You should use the values of 'a' and 'b' to form a key of this dictionary
在这里,我使用了 defaultdict
来累积条目
Here, I have used a defaultdict
to accumulate the entries
l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}]
l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}]
from collections import defaultdict
D = defaultdict(dict)
for lst in l1, l2:
for item in lst:
key = item['a'], item['b']
D[key].update(item)
l3 = D.values()
print l3
输出:
[{'a': 1, 'c': 3, 'b': 2, 'e': 101, 'd': 4}, {'a': 5, 'c': 7, 'b': 6, 'e': 100, 'd': 8}]
这篇关于如何在python中加入2个字典列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文