How to Group List Elements by Key in Python

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:

  1. Sort the List: groupby() works on sorted data. Make sure your list is sorted by the key you want to group by.
  2. Use groupby(): Pass the sorted list and a key function to groupby(). 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}]


Leave a Comment

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

Scroll to Top