In Python, you can group elements of a list by a key using the itertools.groupby()
function. Here’s a simple explanation and example:
Steps:
- Sort the List:
groupby()
works on sorted data. Make sure your list is sorted by the key you want to group by. - Use
groupby()
: Pass the sorted list and a key function togroupby()
. The key function specifies the attribute or property to group by.from itertools import groupby # List of dictionaries data = [ {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Alice', 'age': 28}, {'name': 'Charlie', 'age': 25} ] # Sort the list by 'name' data.sort(key=lambda x: x['name']) # Group by 'name' grouped = groupby(data, key=lambda x: x['name']) # Display groups for key, group in grouped: print(f"{key}: {[item for item in group]}")
Output:
Alice: [{'name': 'Alice', 'age': 25}, {'name': 'Alice', 'age': 28}] Bob: [{'name': 'Bob', 'age': 30}] Charlie: [{'name': 'Charlie', 'age': 25}]