Wells Wells - 2 months ago 12
Python Question

python: list of lists of matching dicts

I have a few dicts like:

a = [ { 'event_id': 1}, { 'event_id': 1}, { 'event_id': 1}, { 'event_id': 2}, { 'event_id': 2}, { 'event_id': 3} ]


I want a list of lists, each sublist containing all the dicts with similar
event_id
values:

[ [ { 'event_id': 1}, { 'event_id': 1}, { 'event_id': 1} ], [ { 'event_id': 2}, { 'event_id': 2} ], [ { 'event_id': 3} ] ]


Is there a quick recipe for this?

Answer

itertools.groupby is perfect for this:

map(lambda x: list(x[1]), (itertools.groupby(a, lambda x: x['event_id'])))
# => [[{'event_id': 1}, {'event_id': 1}, {'event_id': 1}], [{'event_id': 2}, {'event_id': 2}], [{'event_id': 3}]]
Comments