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

Python: match two list of dictionaries by key and merge matched dicts

有两个字典列表,例如

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

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

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

res = [{'id': 1236, 'url': 'directUrl1', 'name': 'ipod touch'}, {'id': 1235, '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, 'url': 'directUrl1', 'name': 'ipod touch'}, {'id': 1235, 'url': 'directUrl2', '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']})

或one-liner:

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

您可以为 big 创建映射,将 id 映射到 name。之后,您可以遍历 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'}]