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><code>itertools.groupby</code> is perfect for this:</p>

<pre><code>map(lambda x: list(x[1]), (itertools.groupby(a, lambda x: x['event_id'])))
# =&gt; [[{'event_id': 1}, {'event_id': 1}, {'event_id': 1}], [{'event_id': 2}, {'event_id': 2}], [{'event_id': 3}]]
</code></pre>

<p>EDIT: As Justin Turner Arthur says in comments, this is not great (mostly because I completely forgot that Python groups only adjacent elements). Please use his solution.</p>

python