我想合并两个字典列表,使用多个键。在
我有一个包含一组结果的dict列表:
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}]
以及另一组结果的dict列表:
^{pr2}$我想用'id'和'year'键将它们组合起来,得到以下信息:
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}]
我知道,要在一个键上组合两个dict列表,我可以使用以下方法:
l1 = {d['id']:d for d in l1}
all = [dict(d, **l1.get(d['id'], {})) for d in l2]
但它忽略了年份,提供了以下错误结果:
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:
l1 = {d['id','year']:d for d in l1}
all = [dict(d, **l1.get(d['id','year'], {})) for d in l2]
如何使用多个键合并?在
您可以根据
id
和year
上的结果列表组合list和groupby。然后将具有相同键的dict合并在一起。在分组可以用^{} 实现,合并可以用^{} 完成
或者,为了避免}
^{pr2}$lambda
,也可以使用^{展开@AlexHall's suggestion,您可以使用
collections.defaultdict
来帮助您:结果
^{pr2}$使用元组
(d['id'], d['year'])
作为键,而不是d['id','year']
。在相关问题 更多 >
编程相关推荐