使用多个键合并python字典的列表

2024-09-25 08:37:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想合并两个字典列表,使用多个键。在

我有一个包含一组结果的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]   

如何使用多个键合并?在


Tags: inidl1列表forget字典all
3条回答

您可以根据idyear上的结果列表组合list和groupby。然后将具有相同键的dict合并在一起。在

分组可以用^{}实现,合并可以用^{}完成

>>> from itertools import groupby
>>> from collections import ChainMap

>>> [dict(ChainMap(*list(g))) for _,g in groupby(sorted(l1+l2, key=lambda x: (x['id'],x['year'])),key=lambda x: (x['id'],x['year']))]
>>> [{'resultA': 2, 'id': 1, 'resultB': 5, 'year': '2017'}, {'resultA': 3, 'id': 1, 'resultB': 7, 'year': '2018'}, {'resultA': 3, 'id': 2, 'resultB': 8, 'year': '2017'}, {'resultA': 5, 'id': 2, 'resultB': 9, 'year': '2018'}]

或者,为了避免lambda,也可以使用^{}

^{pr2}$

展开@AlexHall's suggestion,您可以使用collections.defaultdict来帮助您:

from collections import defaultdict

d = defaultdict(dict)

for i in l1 + l2:
    results = {k: v for k, v in i.items() if k not in ('id', 'year')}
    d[(i['id'], i['year'])].update(results)

结果

^{pr2}$

使用元组(d['id'], d['year'])作为键,而不是d['id','year']。在

相关问题 更多 >