问题描述
我想使用多个键合并两个词典列表.
I want to merge two lists of dictionaries, using multiple keys.
我只有一个字典,其中有一组结果:
I have a single list of dicts with one set of results:
l1 = [{'id': 1, 'year': '2017', 'resultA': 2},
{'id': 2, 'year': '2017', 'resultA': 3},
{'id': 1, 'year': '2018', 'resultA': 3},
{'id': 2, 'year': '2018', 'resultA': 5}]
以及另一组用于另一组结果的字典:
And another list of dicts for another set of results:
l2 = [{'id': 1, 'year': '2017', 'resultB': 5},
{'id': 2, 'year': '2017', 'resultB': 8},
{'id': 1, 'year': '2018', 'resultB': 7},
{'id': 2, 'year': '2018', 'resultB': 9}]
我想使用'id'和'year'键将它们结合起来以得到以下内容:
And I want to combine them using the 'id' and 'year' keys to get the following:
all = [{'id': 1, 'year': '2017', 'resultA': 2, 'resultB': 5},
{'id': 2, 'year': '2017', 'resultA': 3, 'resultB': 8},
{'id': 1, 'year': '2018', 'resultA': 3, 'resultB': 7},
{'id': 2, 'year': '2018', 'resultA': 5, 'resultB': 9}]
我知道,要在一个键上组合两个字典列表,可以使用以下方法:
I know that for combining two lists of dicts on a single key, I can use this:
l1 = {d['id']:d for d in l1}
all = [dict(d, **l1.get(d['id'], {})) for d in l2]
但是它忽略了年份,并提供了以下不正确的结果:
But it ignores the year, providing the following incorrect result:
all = [{'id': 1, 'year': '2018', 'resultA': 3, 'resultB': 5},
{'id': 2, 'year': '2018', 'resultA': 5, 'resultB': 8},
{'id': 1, 'year': '2018', 'resultA': 3, 'resultB': 7},
{'id': 2, 'year': '2018', 'resultA': 5, 'resultB': 9}]
像在R中那样处理它,通过添加要合并的第二个变量,我得到一个KeyError:
Treating this as I would in R, by adding in the second variable I want to merge on, I get a KeyError:
l1 = {d['id','year']:d for d in l1}
all = [dict(d, **l1.get(d['id','year'], {})) for d in l2]
如何使用多个键合并?
推荐答案
使用元组(d['id'], d['year'])
作为密钥,而不是d['id','year']
.
Instead of d['id','year']
, use the tuple (d['id'], d['year'])
as your key.
这篇关于使用多个键合并python字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!