Grouping List of Dictionaries By Specific Key(s) in Python

Ifeoluwa Akande
The Startup
2 min readAug 20, 2020

--

The itertools function in Python provides an efficient way for looping lists, tuples and dictionaries. The itertools.groupby function in itertools will be applied in this tutorial to group a list of dictionaries by a particular key.

To illustrate how this works, we will look at a list of students info (in dictionaries) and try to group these by “class” key such that at the end we will have a list of lists with the inner list being students in the same class.

Please note that the sorted function must be called before the groupby.

import operator
import itertools
d = [{"name":"tobi","class":"1","age":"14", "gender":"m"},{"name":"joke","class":"1","age":"18", "gender":"f"}, {"name":"mary","class":"2","age":"14", "gender":"f"},{"name":"kano","class":"2","age":"15", "gender":"m"},{"name":"ada","class":"1","age":"15", "gender":"f"},{"name":"bola","class":"2","age":"10", "gender":"f"},{"name":"nnamdi","class":"1","age":"15", "gender":"m"}]
d = sorted(d, key=operator.itemgetter("class"))
outputList=[]
for i,g in itertools.groupby(d, key=operator.itemgetter("class")):
outputList.append(list(g))

This same result can be achieved by executing nested looping in some ways, however, “itertools.groupby” function is faster and more efficient — and if I could add, neater.

In the case when two or more python dictionaries are to be considered for the grouping, simply add the remaining keys in the “itemgetter” functions. The following code block shows the case when the students are expected to be grouped by class and gender.

import operator
import itertools
d = [{"name":"tobi","class":"1","age":"14", "gender":"m"},{"name":"joke","class":"1","age":"18", "gender":"f"}, {"name":"mary","class":"2","age":"14", "gender":"f"},{"name":"kano","class":"2","age":"15", "gender":"m"},{"name":"ada","class":"1","age":"15", "gender":"f"},{"name":"bola","class":"2","age":"10", "gender":"f"},{"name":"nnamdi","class":"1","age":"15", "gender":"m"}]d = sorted(d, key=operator.itemgetter("class","gender"))
outputList=[]
for i,g in itertools.groupby(d,key= operator.itemgetter("class","gender")):
outputList.append(list(g))

That’s it!

--

--

Ifeoluwa Akande
The Startup

Data/Machine Learning Engineer. Interested in science, religion and philosophy.