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?
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.
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.
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.
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.
>>> 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]}]
>>> 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]} >>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With