from itertools import groupby # Sample data (must be sorted by the key you want to group by) data = [ {'name': 'Alice', 'city': 'New York'}, {'name': 'Bob', 'city': 'London'}, {'name': 'Charlie', 'city': 'New York'}, {'name': 'David', 'city': 'London'}, {'name': 'Eve', 'city': 'Paris'} ] # Sort the data by 'city' for groupby to work correctly data.sort(key=lambda x: x['city']) print(f"Sorted data: {data} ") grouped_by_city = {} for city, group in groupby(data, key=lambda x: x['city']): grouped_by_city[city] = list(group) # Convert group iterator to a list print(f"Grouped by city: {grouped_by_city}") # Example of printing groups more clearly print(" --- Grouped Output ---") for city, group_items in grouped_by_city.items(): print(f"City: {city}") for item in group_items: print(f" - {item['name']}")