python列表\字典操作

"""
存在列表[{"id": "1", "img": "test1"},{"id": "2", "img": "test2"},{"id": "1", "img": "tes3"},{"id": "2", "img": "tes4"}]
使其根据字典id分组生成新列表:[[{'id': '1', 'img': 'test1'}, {'id': '1', 'img': 'tes3'}], [{'id': '2', 'img': 'test2'}, {'id': '2', 'img': 'tes4'}]]
"""
from itertools import groupby
from operator import itemgetter

list1 = [{"id": "1", "img": "test1"}, {"id": "2", "img": "test2"}, {"id": "1", "img": "tes3"},
         {"id": "2", "img": "tes4"}]
list_sort = sorted(list1, key=lambda x: x['id'])
new_list = []
for i, value in groupby(list_sort, key=itemgetter('id')):
    new_list.append(list(value))

print(new_list)

 

posted @ 2020-08-19 18:03  公子多情,小姐薄命  阅读(118)  评论(0编辑  收藏  举报