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

Malgi

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!

schwobaseggl

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I convert a dictionary into a list of tuples?

How to unpack a dictionary of list (of dictionaries!) and return as grouped tuples?

How do I convert a list of tuples to a dictionary

Convert a list of tuples to a dictionary

How to convert list of tuples to dictionary with index as key

Python convert list of tuples to dictionary with value of multiple tuples

How to create a dictionary of dictionaries using a list of lists and a list of tuples

Convert Nested dictionaries to tuples python

How to convert this dictionary into a list of tuples?

How to extract from this list of tuples and convert into this dictionary?

How to convert lists in a dictionary to dictionaries in a lists (Python)

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

How do I concisely convert a python dictionary to a list of tuples, given a dictionary in which the values may be different types?

list of tuples to dictionary of dictionaries

How to convert a list of 2-tuples into dictionary keys in Python?

How to convert a dictionary into a list of tuples without dict functions? [PYTHON]

Python - how to sort a list of tuples to a dictionary or equivalent?

How to convert a Python multilevel dictionary into tuples?

How to convert a list of lists with tuples into a list of dictionaries?

Convert Dictionary to a list of Tuples

Convert tuples to list of dictionary

python convert list of tuples to composite key dictionary

How to convert list of dictionaries to list of tuples?

How to create list of tuples from dictionary in python?

Python dict comprehension convert list of tuples of dictionaries and integers into list of dictionaries

How to convert a dictionary with keys of type of tuple to a list of dictionaries in python?

Convert list of tuples into a dictionary with list of tuples

How to convert list of elements into dictionary of dictionaries

How to convert a python dictionary with tuples into a pandas dataframe?