Python array of tuples group by first, store second

Viewed 724

So I have an array of tuples something like this

query_results = [("foo", "bar"), ("foo", "qux"), ("baz", "foo")]

I would like to achieve something like:

{
    "foo": ["bar", "qux"],
    "baz": ["foo"]
}

So I have tried using this

from itertools import groupby

grouped_results = {}
for key, y in groupby(query_results, lambda x: x[0]):
    grouped_results[key] = [y[1] for u in list(y)]

The issue I have is although the number of keys are correct, the number of values in each array is dramatically lower than it should be. Can anyone explain why this happens and what I should be doing?

3 Answers
Related