I have python list that contains dictionary paired by “name” and “class” key to represent student data. I need to display all the data group by the “class” key.
Here is the data:
students = [ {'name': 'alex','class': 'A'}, {'name': 'richard','class': 'A'}, {'name': 'john','class': 'C'}, {'name': 'harry','class': 'B'}, {'name': 'rudolf','class': 'B'}, {'name': 'charlie','class': 'E'}, {'name': 'budi','class': 'C'}, {'name': 'gabriel','class': 'B'}, {'name': 'dessy', 'class': 'B'} ]
Python already have a cool built in function called itertools.groupby to solve this kind of problem.
Before we group the data, we have to sort our data by the key. You can refer to my previous post how to sort dictionary by key.
And this is how to group by key:
import itertools from operator import itemgetter students = [ {'name': 'alex','class': 'A'}, {'name': 'richard','class': 'A'}, {'name': 'john','class': 'C'}, {'name': 'harry','class': 'B'}, {'name': 'rudolf','class': 'B'}, {'name': 'charlie','class': 'E'}, {'name': 'budi','class': 'C'}, {'name': 'gabriel','class': 'B'}, {'name': 'dessy', 'class': 'B'} ] # Sort students data by `class` key. students = sorted(students, key=itemgetter('class')) # Display data grouped by `class` for key, value in itertools.groupby(students, key=itemgetter('class')): print key for i in value: print i.get('name') """ results: A alex richard ------- B harry rudolf gabriel dessy ------- C john budi ------- E charlie ------- """
Reference: https://docs.python.org/2/library/itertools.html#itertools.groupby
Leave a comment