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>

<pre><code>from collections import defaultdict

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

if __name__ == '__main__':
    result = defaultdict(list)

    for alphabet, number in data:
        result[alphabet].append(number)
</code></pre>

<p>or without collections module:</p>

<pre><code>if __name__ == '__main__':
    result = {}
    for alphabet, number in data:
        if alphabet not in result:
            result[alphabet] = [number, ]
            continue
        result[alphabet].append(number)
</code></pre>

<p>But i think, that first solution more effective and clear. </p>

python