Converting list of tuples into a dictionary

Question:

I’m looking for a way to convert a list of tuples like this:

[(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]

into a dictionary like this:

{4:[1,2,3] ,15:[4,5,9,11,12], 23:[6,7,8,10]}

The second element from each tuple becomes a dictionary key, and all the first tuple elements associated with that key are stored in a value list.

Can you show me how that can be done?

Asked By: elfuego1

||

Answers:

l = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
d = {}
for v, k in l:
    d.setdefault(k, []).append(v)
Answered By: c089
tuples = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
dicts = {}
for elem in tuples:
    try:
        dicts[elem[1]].append(elem[0])
    except KeyError:
        dicts[elem[1]] = [elem[0],]
Answered By: Adam
>>> a = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
>>> b = {}
>>> for i, j in a:
...     b.setdefault(j, []).append(i)
...
>>> b
{23: [6, 7, 8, 10], 4: [1, 2, 3], 15: [4, 5, 9, 11, 12]}
>>>
Answered By: FogleBird

This will do:

from collections import defaultdict

def to_list_of_dicts(list_of_tuples):
    d = defaultdict(list)
    for x, y in list_of_tuples:
        d[y].append(x)
    return sorted([{x: y} for (x, y) in d.items()])
Answered By: Martin Blech
>>> from collections import defaultdict
>>> l= [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
>>> d= defaultdict( list )
>>> for v, k in l:
...     d[k].append(v)
... 
>>> d
defaultdict(<type 'list'>, {23: [6, 7, 8, 10], 4: [1, 2, 3], 15: [4, 5, 9, 11, 12]})
>>> [ {k:d[k]} for k in sorted(d) ]
[{4: [1, 2, 3]}, {15: [4, 5, 9, 11, 12]}, {23: [6, 7, 8, 10]}]
Answered By: S.Lott

It’s not fancy but it is simple

l = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
d = dict((k, [i[0] for i in l if i[1] == k]) for k in frozenset(j[1] for j in l))

Huzzah!

Answered By: freegnu
for key, value in tuples:
    if d.get(key):
        d[key].append(value)
        continue
    d[key] =[value]
Answered By: Shadowcoder
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.