[英]How do I convert from a list of tuples and integers to a nested dictionary?
I have a list containing tuples and integers我有一个包含元组和整数的列表
eg例如
mylist = [ (('ART', 'bar'), 2), (('ART', 'get'), 1), (('b', 'bet'), 1), (('b', 'chest'), 1), (('b', 'kart'), 2), (('b', 'zee'), 1)]
which I want to convert to this nested dictionary我想转换成这个嵌套字典
my_dict = {
"ART": {"bar": 2, "get": 1},
"b": {"bet": 1, "chest": 1, "kart": 2,"zee": 1}
}
I've been trying to do this using for loops but I'm a beginner and I don't have any experience with nested dictionaries so I really don't know where to start.我一直在尝试使用 for 循环来做到这一点,但我是初学者,而且我对嵌套字典没有任何经验,所以我真的不知道从哪里开始。 I've looked at other questions related to dictionaries of dictionaries eg this and this but the methods suggested aren't working for me (I assume because I am dealing with tuples rather than just lists of lists.)
我已经查看了与字典的字典相关的其他问题,例如this和this但建议的方法对我不起作用(我假设因为我正在处理元组而不仅仅是列表列表。)
You could loop over the input and use setdefault
to populate the dictionary:您可以遍历输入并使用
setdefault
填充字典:
my_dict = {}
for (key, prop), value in mylist:
my_dict.setdefault(key, {})[prop] = value
Try this:尝试这个:
mylist = [ (('ART', 'bar'), 2), (('ART', 'get'), 1), (('b', 'bet'), 1),
(('b', 'chest'), 1), (('b', 'kart'), 2), (('b', 'zee'), 1)]
mydict = dict()
for i in mylist:
if i[0][0] not in mydict.keys():
mydict[i[0][0]] = {i[0][1]: i[1]}
else:
mydict[i[0][0]][i[0][1]] = i[1]
print(mydict)
You can use collections.defaultdict
:您可以使用
collections.defaultdict
:
from collections import defaultdict
my_dict = defaultdict(dict)
for (k1,k2),v in mylist:
my_dict[k1][k2] = v
my_dict = dict(my_dict)
Output: Output:
{'ART': {'bar': 2, 'get': 1}, 'b': {'bet': 1, 'chest': 1, 'kart': 2, 'zee': 1}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.