简体   繁体   中英

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

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.

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}

The answer from @hitter is probably the easiest to understand. As an alternative you can use dictionary comprehensions .

>>> lst = [[0,1,5,0],[4,0,0,7],[0,11]]
>>> {(i, j): lst[i][j] for i in range(len(lst)) for j in range(len(lst[i]))}
{(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}

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