2 回答
TA贡献1798条经验 获得超3个赞
试试这个:
from itertools import product
lookup = {k['id']: v['id'] for k, v in product(l1, l2) if k['email'] == v['email']}
TA贡献1898条经验 获得超8个赞
不一致列表的解决方法:
l1 = [{"email": "email1", "id": 1}, {"email": "email2", "id": 2}, {"email": "email3", "id": 3}]
l2 = [{"email": "email2", "id": 22}, {"email": "email4", "id": 4}, {"email": "email1", "id": 11}, ]
emails = {}
lookup = {}
for el in l1:
emails[el["email"]] = el["id"]
for el in l2:
email = el["email"]
if email in emails:
lookup[emails[email]] = el["id"]
# {1: 11, 2: 22}
print(lookup)
# bad solution from question
lookup = {k['id']: v['id'] for k, v in zip(l1, l2) if k['email'] == v['email']}
# {} - empty
print(lookup)
如果您需要更多列表 - 扩展解决方案,请在最终循环之前更新所有循环的电子邮件字典
添加回答
举报