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

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

本文介绍了将字典分组列表作为基于多个键的字典列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

这篇关于将字典分组列表作为基于多个键的字典列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 06:49