Python 3.x 将字典列表分组为基于多个键的字典列表列表

Python 3.x 将字典列表分组为基于多个键的字典列表列表,python-3.x,list,dictionary,grouping,Python 3.x,List,Dictionary,Grouping,如何根据多个关键元素(性别和类别)将词典列表分组为词典列表 输出 [[{'name': 'tom', 'class': 1, 'roll_no': 1234, 'gender': 'male'}, {'name': 'sam', 'class': 1, 'roll_no': 1212, 'gender': 'male'}], [{'name': 'kavi', 'class': 2, 'roll_no': 1235, 'gender': 'female'}, {'name': 'maha', '

如何根据多个关键元素(性别和类别)将词典列表分组为词典列表

输出

[[{'name': 'tom', 'class': 1, 'roll_no': 1234, 'gender': 'male'}, {'name': 'sam', 'class': 1, 'roll_no': 1212, 'gender': 'male'}], [{'name': 'kavi', 'class': 2, 'roll_no': 1235, 'gender': 'female'}, {'name': 'maha', 'class': 2, 'roll_no': 1211, 'gender': 'female'}]]
import itertools
from itertools import groupby
lst=[{'name':'tom','roll_no':1234,'gender':'male','class':1},
     {'name':'sam','roll_no':1212,'gender':'male','class':1},
     {'name':'kavi','roll_no':1235,'gender':'female','class':2},
     {'name':'maha','roll_no':1211,'gender':'female','class':2}]
keyfunc = key=lambda x:(x['class'],x['gender'])
final_lst = [list(grp) for key, grp in itertools.groupby(sorted(lst, key=keyfunc),key=keyfunc)]
print(final_lst)
[[{'name': 'tom', 'class': 1, 'roll_no': 1234, 'gender': 'male'}, {'name': 'sam', 'class': 1, 'roll_no': 1212, 'gender': 'male'}], [{'name': 'kavi', 'class': 2, 'roll_no': 1235, 'gender': 'female'}, {'name': 'maha', 'class': 2, 'roll_no': 1211, 'gender': 'female'}]]