Naive approach to convert a Python list of lists to a dictionary

Fritjof Larsson :

Suppose I have a list like this lst = [[0,1,5,0], [4,0,0,7], [0,11]]. I want to create a dictionary, where the key is a tuple (i, j) and the value is lst[i][j]. It should show something like this d = {(0,0): 0, (0, 1): 1, (0,2): 5, (0,3): 0 ... (2,1): 11} I believe you got the pattern now. My attempt to produce something like this goes as fellows:

def convert(lst):
    d = dict()
    for i in range(len(lst)):
        for j in range(i):
            d(i, j)] = lst[i][j]
    return d

Which doesn't work. It doesn't sweep through the whole list. Kindly help me find the problem with my humble code.

hitter :

Your code in question is almost correct, take a look at the code below, which makes a slight adjustment:

def convert(lst):
    d = {}
    for i in range(len(lst)):
        for j in range(len(lst[i])): # This is the part that differentiates.
            d[(i, j)] = lst[i][j]
    return d

lst = [[0,1,5,0], [4,0,0,7], [0,11]]
print(convert(lst))

When run this outputs:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169545&siteId=1