Search code examples
pythonlistdictionarykeyerror

Python KeyError when converting list of list to dictionary


I'm stuck with this simple task. I have a list of lists and I need to convert it to a dictionary but so far without any success.

I tried it with the code below, but it gives me KeyError:0

list = [[3,0,7,4,5],[2,3,0,1,2],[6,6,7,6,6]]

d = {}
for x in list:
    i = 0
    for number in x:
        d[i].append(number)
        i += 1

I need it to be like this:

{0: [3,2,6], 1: [0,3,6], 2: [7,0,7], 3: [4,1,6], 4: [5,2,6]}

Any help is appreciated, thanks in advance!


Solution

  • Just as a side note, you can do this quite simply by using the enumerate and zip functions.

    lst = [[3, 0, 7, 4, 5], [2, 3, 0, 1, 2], [6, 6, 7, 6, 6]]
    d = dict(enumerate(zip(*lst)))
    
    • zip(*lst) is basically a transpose function. It returns a list in Python 2, or a zip object in Python 3, which can be converted into the equivalent list.

      [(3, 2, 6), (0, 3, 6), (7, 0, 7), (4, 1, 6), (5, 2, 6)]
      
    • enumerate() basically just tacks the index of an element before it, and returns an enumerate object, which when converted into a list returns a list of tuples.

      [(0, (3, 2, 6)), (1, (0, 3, 6)), (2, (7, 0, 7)), (3, (4, 1, 6)), (4, (5, 2, 6))]
      
    • dict() takes a list of tuples and turns them into key/value pairs.

      {0: (3, 2, 6), 1: (0, 3, 6), 2: (7, 0, 7), 3: (4, 1, 6), 4: (5, 2, 6)}