Python 3.x 匹配两个字典的值,并使用匹配的键值对更新其中一个字典内的列表

Python 3.x 匹配两个字典的值,并使用匹配的键值对更新其中一个字典内的列表,python-3.x,Python 3.x,你好,我已经尝试了一段时间来解决这个问题,但运气不好,因此非常感谢您的帮助 尝试将aa词典列表的标题与bb词典列表的标题进行匹配,并将aa词典列表更新为键值组合 aa = [{'link': 'www.home.com', 'title': ['one', 'two', 'three']}, {'link': 'www.away.com', 'title':['two', 'three']}] bb = [{'id': 1, 'title' :'one'},{'id': 2, 'title':

你好,我已经尝试了一段时间来解决这个问题,但运气不好,因此非常感谢您的帮助

尝试将aa词典列表的标题与bb词典列表的标题进行匹配,并将aa词典列表更新为键值组合

aa = [{'link': 'www.home.com', 'title': ['one', 'two', 'three']}, {'link': 'www.away.com', 'title':['two', 'three']}]

bb = [{'id': 1, 'title' :'one'},{'id': 2, 'title': 'two'}, {'id': 3, 'title': 'three'}]


result = [{'link':'www.home.com', 'title':[{'one': 1, 'two': 2, 'three': 3}]}, {'link': 'www.away.com', 'title':[{'two': 2, 'three': 3}]}
]结果是:

result = [{'link': 'www.home.com', 'title': [{'one': 1, 'two': 2, 'three': 3}]}, {'link': 'www.away.com', 'title': [{'two': 2, 'three': 3}]}]
请参阅我的代码,如下所示:

from copy import deepcopy

aa = [{'link': 'www.home.com', 'title': ['one', 'two', 'three']}, {'link': 'www.away.com', 'title':['two', 'three']}]
bb = [{'id': 1, 'title' :'one'},{'id': 2, 'title': 'two'}, {'id': 3, 'title': 'three'}]

titleids = {}
for b in bb:
    titleids[b['title']] = b['id']

result = deepcopy(aa)
for a in result:
    a['title'] = [{title:titleids[title] for title in a['title']}]

print(result)
为了解决此示例,您将执行以下操作:

[ {'link':l['link'],'title':{i:b1[i] for i in l["title"]}} for l in aa]

[{'link': 'www.home.com', 'title': {'one': 1, 'two': 2, 'three': 3}}, {'link': 'www.away.com', 'title': {'two': 2, 'three': 3}}]
[{i:({k:b1[k] for k in j} if i is 'title' else j) for i,j in l.items()} for l in aa]

[{'link': 'www.home.com', 'title': {'one': 1, 'two': 2, 'three': 3}}, {'link': 'www.away.com', 'title': {'two': 2, 'three': 3}}]
虽然如果您有许多其他钥匙,您可以:

[ {'link':l['link'],'title':{i:b1[i] for i in l["title"]}} for l in aa]

[{'link': 'www.home.com', 'title': {'one': 1, 'two': 2, 'three': 3}}, {'link': 'www.away.com', 'title': {'two': 2, 'three': 3}}]
[{i:({k:b1[k] for k in j} if i is 'title' else j) for i,j in l.items()} for l in aa]

[{'link': 'www.home.com', 'title': {'one': 1, 'two': 2, 'three': 3}}, {'link': 'www.away.com', 'title': {'two': 2, 'three': 3}}]

下面两种解决方案都有效,谢谢大家的帮助!