将字典分组列表作为基于多个键的字典列表列表

时间:2018-12-31 04:48:17

标签: python-3.x list dictionary grouping

如何基于多个关键要素(性别和阶级)将字典列表分组为字典列表列表?

input = [{'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}]

expected_output =[[
          {'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}]

1 个答案:

答案 0 :(得分:1)

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'}]]