简体   繁体   中英

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!

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

setdefault is your friend:

d = {}
for t in l:
    d.setdefault(t[0],{})[t[1]]=t[2]

If you want to do it in one (rather long) line, you can use itertools.groupby , but remember that the list has to be sorted by the key for this to work:

>>> lst = [(1, 'a', 22), (2, 'b', 56), (1, 'b', 34), (2, 'c', 78), (3, 'd', 47)]
>>> {key: {v[1]: v[2] for v in vals} for key, vals in itertools.groupby(sorted(lst), key=operator.itemgetter(0))}
{1: {'a': 22, 'b': 34}, 2: {'b': 56, 'c': 78}, 3: {'d': 47}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM