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>You can use <code>defaultdict</code> from the <code>collections</code> module for this:</p>

<pre><code>from collections import defaultdict

l = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)]
d = defaultdict(list)

for k,v in l:
    d[k].append(v)

for k,v in d.items():
    exec(k + "list=" + str(v))
</code></pre>

python