Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting list of tuples into a dictionary

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?

like image 421
elfuego1 Avatar asked Aug 05 '09 14:08

elfuego1


People also ask

How do I convert a list to a dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

Can a tuple with a list be a key in a dictionary?

A tuple containing a list cannot be used as a key in a dictionary. Answer: True. A list is mutable. Therefore, a tuple containing a list cannot be used as a key in a dictionary.

Can you have a dictionary of tuples?

In Python the dict() method takes a list of tuples as an argument and each tuple store key-value pair element and it returns into a dictionary.

How do I turn a list of tuples into a list?

If you're in a hurry, here's the short answer:Use the list comprehension statement [list(x) for x in tuples] to convert each tuple in tuples to a list. This also works for a list of tuples with a varying number of elements.


2 Answers

>>> 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]}] 
like image 82
S.Lott Avatar answered Oct 14 '22 14:10

S.Lott


>>> 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]} >>> 
like image 26
FogleBird Avatar answered Oct 14 '22 16:10

FogleBird