2024-03-29 01:05:06 发布
网友
建立一个ID字典,然后检查它们:
>>> a_list=[ ... [{'id':'123', 'user':'Foo'}, {'id':'123','user':'Jonny'}, ], ... [{'id':'456', 'user':'Bar'}, {'id':'456','user':'Mary'},], ... ] >>> b_list=[{'post':'123','text': 'Something'}, {'post':'456', 'text':'Another thing'}, ] >>> d = {l[0]['id']:l for l in a_list} >>> for item in b_list: ... item['comments'] = d[item['post']] ... >>> import pprint >>> pprint.pprint(b_list) [{'comments': [{'id': '123', 'user': 'Foo'}, {'id': '123', 'user': 'Jonny'}], 'post': '123', 'text': 'Something'}, {'comments': [{'id': '456', 'user': 'Bar'}, {'id': '456', 'user': 'Mary'}], 'post': '456', 'text': 'Another thing'}]
我假设在a_list中,一个嵌套的list将具有相同的'id',并且每个id只有一个列表。
a_list
list
'id'
为了实现这一点,迭代b_列表并检查a_list中的匹配。如果匹配,则向a_list的dict对象添加值
>>> a_list=[ ... [{'id':'123', 'user':'Foo'}, {'id':'123','user':'Jonny'}], ... [{'id':'456', 'user':'Bar'}, {'id':'456','user':'Mary'}], ... ] >>> b_list=[{'post':'123','text': 'Something'}, {'post':'456', 'text': 'Another thing'}] >>> >>> for dict_item in b_list: ... id = dict_item['post'] ... for list_item in a_list: ... if list_item[0]['id'] == id: ... dict_item['comments'] = list_item ... break ... >>> b_list [{ 'text': 'Something', 'post': '123', 'comments': [ { 'id': '123', 'user': 'Foo' }, { 'id': '123', 'user': 'Jonny' } ] }, { 'post': '456', 'text': 'Another thing', 'comments': [ { 'id': '456', 'user': 'Bar' }, { 'id': '456', 'user': 'Mary' } ] } ]
建立一个ID字典,然后检查它们:
我假设在
a_list
中,一个嵌套的list
将具有相同的'id'
,并且每个id只有一个列表。为了实现这一点,迭代b_列表并检查
a_list
中的匹配。如果匹配,则向a_list
的dict对象添加值相关问题 更多 >
编程相关推荐