gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:25:20 31 4
gpt4 key购买 nike

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

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

最佳答案

试试这个:

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

关于python - 如果其他元素使用理解匹配,则从两个字典列表中提取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53413594/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com