How To Group List Of Tuples?
Note: I know how I can do this of course in an explicit for loop but I am looking for a solution that is a bit more readable. If possible, I'd like to solve this by using some of t
Solution 1:
The simplest solution is probably not to use groupby
at all.
from collections import defaultdict
d = defaultdict(list)
for k, v in my_tuples:
d[k].append(v)
The reason I wouldn't use groupby
is because groupby(iterable)
groups items in iterable
that are adjacent. So to get all of the 'C'
values together, you would first have to sort your list. Unless you have some reason to use groupby
, it's unnecessary.
Solution 2:
You should use collections.defaultdict
for an O(n) solution, see @PatrickHaugh's answer.
Using itertools.groupby
requires sorting before grouping, incurring O(n log n) complexity:
from itertools import groupby
from operator import itemgetter
sorter = sorted(my_tuples, key=itemgetter(0))
grouper = groupby(sorter, key=itemgetter(0))
res = {k: list(map(itemgetter(1), v)) for k, v in grouper}
print(res)
{'A': [74, 23, 2],
'B': [52],
'C': [74, 87, 99, 21, 1, 87]}
Post a Comment for "How To Group List Of Tuples?"