简体   繁体   English

如何在Python中将列表列表转换为dict

[英]How to convert list of list to dict of dict in Python

I'm not very sure how to explain it in words, what I'm trying to do is convert this: 我不太确定如何用语言解释它,我想做的是将其转换为:

my_list = [['a','b',1],['a','c',2],['b','a',3],['b','c',4]]

Into something like this: 变成这样的东西:

my_dict = {'a':{'b':1,'c':2},'b':{'a':3,'c':4}}

I've tried 我试过了

for item in my_list:
   my_dict[item[0]]= {item[1]:item[2]}

but it's not giving the result I want. 却没有达到我想要的结果。

When a key is already in the dict, you need to use .update instead of replacing the value with a new one. 当字典中已经有一个键时,您需要使用.update而不是用新的键替换值。

>>> my_list = [['a', 'b', 1], ['a', 'c', 2], ['b', 'a', 3], ['b', 'c', 4]]
>>> my_dict = {}
>>> for item in my_list:
...     try:
...         my_dict[item[0]].update({item[1]: item[2]})
...     except KeyError:
...         my_dict[item[0]] = {item[1]: item[2]}
... 
>>> my_dict
{'b': {'c': 4, 'a': 3}, 'a': {'b': 1, 'c': 2}}

In general you should start with a collections.defaultdict that returns an empty dictionary for any missing elements. 通常,您应该以collections.defaultdict开头,它为所有缺少的元素返回一个空字典。

Then you can iterate through your outer list getting the entry for the first list element of the sub-list and setting the value of that dictionaries entry for the second element to the value of the 3rd element. 然后,您可以遍历外部列表,以获取子列表的第一个列表元素的条目,并将第二个元素的字典条目的值设置为第三个元素的值。

The issue with the solution you came up with is that you are overwriting the inner dictionary each time you encounter the same key in the outer one. 您提出的解决方案的问题是,每次在外部字典中遇到相同的键时,您都会覆盖内部字典。 Rather than using 而不是使用

my_dict[item[0]]={item[1]:item[2]}

You need to use the .setdefault method so it will create the dict if it doesn't exist, and just get it if it does. 您需要使用.setdefault方法,以便它在不存在dict时创建dict,在不存在的情况下仅获取它。 Then you can update it with the new key-value pairs. 然后,您可以使用新的键值对对其进行更新。

my_dict.setdefault(item[0], {})[item[1]] = item[2]
my_list = [['a','b',1],['a','c',2],['b','a',3],['b','c',4]]

my_dict = {}
for item in my_list:
    if item[0] not in my_dict:
        my_dict[item[0]]= {item[1]:item[2]}
    else:
        my_dict[item[0]][item[1]] = item[2]


print(my_dict)

output: 输出:

{'b': {'c': 4, 'a': 3}, 'a': {'b': 1, 'c': 2}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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