I have a list of tuples like:
[(1, 'a', 22), (2, 'b', 56), (1, 'b', 34), (2, 'c', 78), (3, 'd', 47)]
and I need to convert it to:
{1: {'a': 22, 'b': 34}, 2: {'b': 56, 'c': 78}, 3: {'d': 47}}
Is that possible in Python? Thanks!
In Python, use the dict() function to convert a tuple to a dictionary. A dictionary object can be created with the dict() function. The dictionary is returned by the dict() method, which takes a tuple of tuples as an argument.
To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.
One of the built-in methods for dictionaries is the . items() methods, which returns a tuple of tuples of the key value pairs found inside the dictionary. We can use this method and pass it into the list() function, in order to generate a list of tuples that contain the key value pairs from our dictionary.
Use a defaultdict:
from collections import defaultdict
l = [(1, 'a', 22), (2, 'b', 56), (1, 'b', 34), (2, 'c', 78), (3, 'd', 47)]
d = defaultdict(dict)
for x, y, z in l:
d[x][y] = z
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