如何迭代两个字典列表,通过键匹配列表之间的字典,如果匹配,则将每个字典中的特定键附加到新字典中的键值对中。让我用一个例子来澄清:
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']}
呼如林
汪汪一只猫
相关分类