views:

50

answers:

1

I want to group by on dict key

>>> x
[{'a': 10, 'b': 90}, {'a': 20}, {'a': 30}, {'a': 10}]
>>> [(name, list(group)) for name, group in groupby(x, lambda p:p['a'])]
[(10, [{'a': 10, 'b': 90}]), (20, [{'a': 20}]), (30, [{'a': 30}]), (10, [{'a': 10}])]

This must group on key 10 :(

+4  A: 

docs say:

itertools.groupby:
It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.

SilentGhost
>>> x.sort(key=lambda x:x['a'])>>> [(name, list(group)) for name, group in groupby(x, lambda p:p['a'])][(10, [{'a': 10, 'b': 90}, {'a': 10}]), (20, [{'a': 20}]), (30, [{'a': 30}])]This code solve my problem thx for your support :)
Nil