您好,在一段时间内尝试解决这个问题并没有多大运气,因此非常感谢您的帮助。
尝试将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}]}
]
答案 0 :(得分:1)
结果是:
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)
答案 1 :(得分:0)
b1={k["title"]:k["id"] for k in bb}
为了解决这个例子,您将要做:
[ {'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}}]