-1

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.

Chad S.
  • 6,252
  • 15
  • 25
Maw Ceron
  • 319
  • 3
  • 9
  • 4
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask]. – Morgan Thrapp Dec 09 '15 at 18:44
  • See [recursive access to dictionary and modification](https://stackoverflow.com/a/23013719) for a technique that would solve this for you; `for parent, child, value in my_list: set_nested(my_dict, (parent, child), value)`. – Martijn Pieters Dec 09 '15 at 18:50

4 Answers4

2

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}}
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

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.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
1

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]
Chad S.
  • 6,252
  • 15
  • 25
0
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}}
Riccati
  • 461
  • 4
  • 13