Menu Close

How to use the itertools.groupby() method with Python?

Sometimes, we want to use the itertools.groupby() method with Python.

In this article, we’ll look at how to use the itertools.groupby() method with Python.

How to use the itertools.groupby() method with Python?

To use the itertools.groupby() method with Python, we can call it with an array of tuples and a function to do the grouping.

For instance, we write:

from itertools import groupby

things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"),
          ("vehicle", "speed boat"), ("vehicle", "school bus")]

groups = [(k, [*g]) for k, g in groupby(things, lambda x: x[0])]
print(groups)

We use list comprehension to get the key and group items from g with the * operator.

We call groupby with things and a function that returns the key of the items to group by, which is the first entry in each tuple.

Therefore, groups is:

[('animal', [('animal', 'bear'), ('animal', 'duck')]), ('plant', [('plant', 'cactus')]), ('vehicle', [('vehicle', 'speed boat'), ('vehicle', 'school bus')])]

Conclusion

To use the itertools.groupby() method with Python, we can call it with an array of tuples and a function to do the grouping.

Posted in Python, Python Answers