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

时间:2018-11-21 13:52:03

标签: python dictionary list-comprehension

我如何遍历两个字典列表,用一个键匹配列表之间的字典,如果匹配,则将每个字典的特定键附加到新字典的键值对中。让我用一个例子来阐明:

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

2 个答案:

答案 0 :(得分:1)

尝试一下:

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

答案 1 :(得分:1)

不一致列表的解决方案:

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)

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