Mahamutha M
Mahamutha M

Reputation: 1287

Group list of dictionary as list of list of dictionary based on multiple keys

How to group list of dictionary as list of list of dictionary based on multiple key elements(gender & class)?

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

Upvotes: 0

Views: 96

Answers (1)

Bitto
Bitto

Reputation: 8205

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)

Output

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

Upvotes: 1

Related Questions