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

如何迭代两个字典列表,通过键匹配列表之间的字典,如果匹配,则将每个字典中的特定键附加到新字典中的键值对中。让我用一个例子来澄清:


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's


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


FFIVE
浏览 171回答 2
2回答

呼如林

试试这个:from itertools import productlookup = {k['id']: v['id'] for k, v in product(l1, l2) if k['email'] == v['email']}

汪汪一只猫

不一致列表的解决方法: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 questionlookup = {k['id']: v['id'] for k, v in zip(l1, l2) if k['email'] == v['email']}# {} - emptyprint(lookup)如果您需要更多列表 - 扩展解决方案,请在最终循环之前更新所有循环的电子邮件字典
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python