Python groupby has surprising behavior

Python’s groupby from itertools has surprising behavior if you compare it to other languages’ group by implementations.

Consider this Python snippet that groups objects by a key and then prints each key with its group.

friends = [
    {"couple_id": 3, "name": "John"},
    {"couple_id": 1, "name": "Thomas"},
    {"couple_id": 2, "name": "Eugene"},
    {"couple_id": 2, "name": "Beatrice"},
    {"couple_id": 1, "name": "Imani"},
    {"couple_id": 3, "name": "Mary"}
]

friends_groups = groupby(friends, lambda x: x["couple_id"])

for key, grouping in friends_groups:
    print(key, " --> ", " loves ".join([obj["name"] for obj in grouping]))
[Read More]