I am supposed to convert a nested list into a dictionary. If I have the list:
data=[[['1','2','-2'], ['3','-1','4']]
I want it to become:
d={(0, 0): 1, (0, 1): 3, (1, 0): 2, (1, 1): -1, (2, 0): -2, (2, 1): 4}
The tricky part is I you need to see this list as a matrix:
'1','2','-2'
'3','-1','4'
So the keys in the dictionary should be their position in that matrix. I am confused and I tried:
for m in range(len(data)):
for n in range(len(data[m])):
d[(m,n)]= data[n][m]
I know it's wrong because it will become out of range. I am so struggling with it.
Your current data
is invalid syntax, however, I believe this is what you are looking for:
data= [['1','2','-2'], ['3','-1','4']]
new_result = {(a, i):data[i][a] for i in range(len(data)) for a in range(len(data[0]))}
Output:
{(0, 1): '3', (0, 0): '1', (2, 1): '4', (2, 0): '-2', (1, 0): '2', (1, 1): '-1'}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments