简体   繁体   中英

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.

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

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. 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}}

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