Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list of tuples to a dictionary of dictionaries in Python?

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!

like image 917
Malgi Avatar asked May 01 '16 17:05

Malgi


People also ask

How do you convert a tuple to a dictionary in Python?

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.

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

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.

How we can create a list of tuples from the values of a dictionary of lists?

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.


1 Answers

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
like image 59
user2390182 Avatar answered Sep 26 '22 19:09

user2390182