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

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}]

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}]

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]

How do I merge using multiple keys?

解决方案

Instead of d['id','year'], use the tuple (d['id'], d['year']) as your key.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值