[英]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? 这可能在Python中吗? Thanks!
谢谢!
Use a defaultdict : 使用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: setdefault
是你的朋友:
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: 如果你想在一个(相当长的)行中执行它,你可以使用
itertools.groupby
,但是请记住,列表必须按键进行sorted
才能使用:
>>> 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}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.