سؤال

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!

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

Please don't use built-ins as IDs.

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

You're getting the KeyError the first time you call:

d[i].append(number)

This is because there is no key i in d. Rather than fix up this code, let's look at using enumerate() and zip(), which is perhaps more "Pythonic":

>>> d = dict(enumerate(zip(*lst)))
>>> d
{0: (3, 2, 6), 1: (0, 3, 6), 2: (7, 0, 7), 3: (4, 1, 6), 4: (5, 2, 6)}

Perhaps this is a little daunting for a new Python user. Let me break it down.

>>> zip(*lst)
[(3, 2, 6), (0, 3, 6), (7, 0, 7), (4, 1, 6), (5, 2, 6)]

This unpacks the list into zip(), which "zips" the three smaller lists together.

>>> enumerate(zip(*lst)

This returns an iterator of pairs. Each pair is an index (starting with 0) and an item from the input.

>>> dict(enumerate(zip(*lst)))

The dict() function returns a new dictionary object, initialised with the key-value pairs passed in.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top