CodexBloom - Programming Q&A Platform

ValueError when using itertools.groupby in Python 3.9 with custom sort key

👀 Views: 4 đŸ’Ŧ Answers: 1 📅 Created: 2025-05-31
python itertools groupby Python

I'm trying to use the `itertools.groupby` function to group a list of dictionaries based on a custom sort key, but I'm working with a `ValueError: too many values to unpack (expected 2)` when I iterate over the groups. I have ensured that my input list is sorted by the key function, but something still seems off. Here's the code snippet I'm working with: ```python import itertools data = [ {'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 25}, {'name': 'David', 'age': 30}, ] # I want to group by age sorted_data = sorted(data, key=lambda x: x['age']) # Attempting to group the sorted data grouped_data = itertools.groupby(sorted_data, key=lambda x: x['age']) for age, group in grouped_data: print(f'Age: {age}') for person in group: print(f' {person}') ``` I expected this to print the ages and their corresponding names grouped correctly, but instead, I'm getting the behavior mentioned above. I've confirmed that my input data is correctly sorted by age before calling `groupby`. Can someone guide to understand why I'm getting this unpacking behavior? Is there a specific requirement for the input to `groupby` that I might be missing? I'm running Python 3.9.7. Any insights would be greatly appreciated!