微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python:按键匹配两个字典列表并合并匹配的字典

如何解决Python:按键匹配两个字典列表并合并匹配的字典

具有两个类似的字典列表

big = [{'id': 1234,'name': 'ipod'},{'id': 1235,'name': 'ipod x'},{'id': 1236,'name': 'ipod touch'}]

small = [{'id': 1236,'url': 'directUrl1'},'url': 'directUrl2'}]

我想实现一种高效且Python化的方式来查找两个列表(基于id)之间的交集并创建合并字典的新列表:

res = [{'id': 1236,'url': 'directUrl1','name': 'ipod touch'},'url': 'directUrl2','name': 'ipod x'}]

我目前的做法:

>>> res = []
>>>
>>> for item in [x for x in small if x['id'] in [y['id'] for y in big]]:
...  res.append({**item,**[x for x in big if x['id'] == item['id']][0]})
...
>>> res
[{'id': 1236,'name': 'ipod x'}]

解决方法

Pythonic并不意味着致密;)

怎么样:

new_dictlist = []
for d1 in small:
    for d2 in big:
        if d1['id'] == d2['id']:
            new_dictlist.append({'id':d1['id'],'url':d1['url'],'name':d2['name']})

或单线:

[{**x,**y} for x in big for y in small if x['id'] == y['id']]
,

您可以为big创建一个将idname映射的映射。之后,您可以遍历small列表并构建新的词典列表。

>>> big_map = {d['id']:d['name'] for d in big}
>>> res = [{'id': d['id'],'url':d['url'],'name':big_map[d['id']]} for d in small if d['id'] in big_map]
>>> res
[{'id': 1236,'url': 'directUrl1','name': 'ipod touch'},{'id': 1235,'url': 'directUrl2','name': 'ipod x'}]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。