Create a list from an existing list of key value pairs in python
<p>I am trying to come up with a neat way of doing this in python.</p>

<p>I have a list of pairs of alphabets and numbers that look like this :</p>

<pre><code>[(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)]
</code></pre>

<p>What I want to do is to create a new list for each alphabet and append all the numerical values to it.</p>

<p>So, output should look like:</p>

<pre><code>alist = [1,2,3]
blist = [10,100]
clist = [99]
dlist = [-1,-2]
</code></pre>

<p>Is there a neat way of doing this in Python?</p>

<p>If you want to avoid using a <code>defaultdict</code> but are comfortable using <code>itertools</code>, you can do it with a one-liner</p>

<pre><code>from itertools import groupby

data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)]
grouped = dict((key, list(pair[1] for pair in values)) for (key, values) in groupby(data, lambda pair: pair[0]))
# gives {'b': [10, 100], 'a': [1, 2, 3], 'c': [99], 'd': [-1, -2]}
</code></pre>

python