Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *