python: list of lists of matching dicts
<p>I have a few dicts like:</p>

<p><code>a = [ { 'event_id': 1}, { 'event_id': 1}, { 'event_id': 1}, { 'event_id': 2}, { 'event_id': 2}, { 'event_id': 3} ]</code></p>

<p>I want a list of lists, each sublist containing all the dicts with similar <code>event_id</code> values:</p>

<p><code>[ [ { 'event_id': 1}, { 'event_id': 1}, { 'event_id': 1} ], [ { 'event_id': 2}, { 'event_id': 2} ], [ { 'event_id': 3} ] ]</code></p>

<p>Is there a quick recipe for this?</p>

<p>As <a href="http://stackoverflow.com/a/39823731/1843865">amadan suggests</a>, <code>itertools.groupby</code> is a great approach to this problem. It takes an iterable and a key function to group by. You'll first want to make sure your list is sorted by the same key so that groupby doesn't end up creating multiple groups for the same key (similar to how you do an ORDER BY before a GROUP BY in SQL).</p>

<pre><code>from itertools import groupby
from operator import itemgetter

grouping_key = itemgetter('event_id')  # produces a function like lambda x: x['event_id']

# If your events weren't already ordered with adjacent 'event_id's:
ordered_a = sorted(a, key=grouping_key)

grouped_a = [list(group) for _grouper, group in groupby(ordered_a, key=grouping_key)]
</code></pre>

python