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)