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!
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.
Comments