如何在python中加入两个dict列表?
我有两个类似的列表:如何在python中加入两个dict列表?,python,list,python-2.7,Python,List,Python 2.7,我有两个类似的列表: 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中相等 i、 e 我怎样才能做到这一点呢?你应该把结果积累到字典里。您应该使用“a”和“b”的值来构成此词典的键 在这里,我
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
中相等
i、 e
我怎样才能做到这一点呢?你应该把结果积累到字典里。您应该使用“a”和“b”的值来构成此词典的键 在这里,我使用了
defaultdict
来累积条目
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}]
我的方法是按键对组合列表进行排序,即键
a
+b
。之后,对于具有相似键的每组词典,将它们组合起来:
from itertools import groupby
def ab_key(dic):
return dic['a'], dic['b']
def combine_lists_of_dicts(list_of_dic1, list_of_dic2, keyfunc):
for key, dic_of_same_key in groupby(sorted(list_of_dic1 + list_of_dic2, key=keyfunc), keyfunc):
combined_dic = {}
for dic in dic_of_same_key:
combined_dic.update(dic)
yield combined_dic
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}]
for dic in combine_lists_of_dicts(l1, l2, ab_key):
print dic
讨论
- 函数
返回键ab_key
和a
的值元组,用于对分组进行排序b
功能将具有相似键的所有词典分组在一起groupby
- 此解决方案的效率不如John La Rooy,但对于小列表应该可以很好地工作
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 = []
for i in range(len(l1)):
for j in range(len(l2)):
if l1[i]['a'] == l2[j]['a'] and l1[i]['b'] == l2[j]['b']:
l3.append(dict(l1[i]))
l3[i].update(l2[j])
使用熊猫可以实现一个好的、快速的解决方案
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}]
import pandas as pd
pd.DataFrame(l1).merge(pd.DataFrame(l2), on=['a','b']).to_dict('records')
您应该使用
==
而不是is
进行比较values@JohnLaRooy,但我记得有一次我读到“is”比“==”…可能不是,因为is
只比较身份。在这里,您只能侥幸逃脱,因为您使用非常小的int
值进行测试<代码>=是比较值的唯一方法correctly@JohnLaRooy...Alright,谢谢你的提醒……)
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}]
import pandas as pd
pd.DataFrame(l1).merge(pd.DataFrame(l2), on=['a','b']).to_dict('records')