Reputation: 182
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.
Upvotes: 2
Views: 194
Reputation: 2812
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}
Upvotes: 6
Reputation: 2365
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}
Upvotes: 2