为了账号安全,请及时绑定邮箱和手机立即绑定

如果其他元素使用理解匹配,则从两个字典列表中提取元素

如果其他元素使用理解匹配,则从两个字典列表中提取元素

FFIVE 2021-08-24 16:30:46
如何迭代两个字典列表,通过键匹配列表之间的字典,如果匹配,则将每个字典中的特定键附加到新字典中的键值对中。让我用一个例子来澄清:l1 = [{'id': 52, 'email': 'someemail@yahoo.com', 'anotherfield': 'some value'},       .....      {'id': 98, 'email': 'anotheremail@yahoo.com', 'anotherfield': 'another value'}]l2 = [{'id': 93, 'email': 'someemail@yahoo.com', 'another key': 'seventeen'},       .....      {'id': 101, 'email': 'anotheremail@yahoo.com', 'another key': 'twenty'}]# match the 'email' keys between each list, and if match, create k, v pair from id'sdesired_output = {'52': 93.....'98': 101}通过简单地迭代每个列表,我可以很容易地实现这一点,如下所示:lookup = dict()for l in l1:    for p in l2:        if l['email']==p['email']:            lookup[l['id']]=p['id']            break但是,这有点笨拙,我更喜欢某种理解。我的尝试:lookup = {k['id']: v['id'] for k, v in zip(l1, l2) if k['email'] == v['email']}
查看完整描述

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


查看完整回答
反对 回复 2021-08-24
?
汪汪一只猫

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)

如果您需要更多列表 - 扩展解决方案,请在最终循环之前更新所有循环的电子邮件字典


查看完整回答
反对 回复 2021-08-24
  • 2 回答
  • 0 关注
  • 170 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信