I am struggling to find a convincing pythonic way to do group by on a list of dict, below seems to be having good readability but not necessary the most efficient way: I have to sort first ( the prerequisite for groupby) and then do the group by (another questiona mark here for the how groupby in itertools is implemented..).
One obvious alternative is to use collections.defaultdict but I will have to do a lot of list.append (and less pythonic?). which one you guy think it a better option? or there is other better way to do group by? thanks
from itertools import groupby
from operator import itemgetter
data = [ {'x':1, 'y':1},
{'x':2, 'y':2},
{'x':3, 'y':2},
{'x':4, 'y':1}, ]
sortedData = sorted(data, key=itemgetter('y'))
for y, d in groupby( sortedData, itemgetter('y')):
print y, list(d)
1 [{'y': 1, 'x': 1}, {'y': 1, 'x': 4}]
2 [{'y': 2, 'x': 2}, {'y': 2, 'x': 3}]
list.append
, when you canyield
, or equivalently, use list comprehensions? – user824425 Jan 3 '13 at 21:53[y, list(d) for y, d in groupby(sortedData, itemgetter('y'))]
(modulo correct syntax, of course)? – user824425 Jan 3 '13 at 22:53