Reputation: 199
I have two dictionaries named 'I' and 'J' and I want to iterate it over a for loop and get the value of a variable which is function of both 'I' and 'J'.
I={0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150}
J={-50,-40,-30,-20,-10,0,10,20,30,40}
F=[[0 for j in J] for i in I]
for i in I:
for j in J:
if i+j==100:
F[i][j]=-j*2.782490319
else:
F[i][j]="NA"
print(F[60][40])
I want the value in the print command to be taken from dictionary 'I' & 'J'. For example in above code I have written print(F[60][40]), so the 60 can be any value from dictionary 'I' and 40 can be any value from dictionary 'J'.
I was expecting the answer for above code to be "-111.29961276" but instead I am getting an error "IndexError: list index out of range". I would be more than happy if somebody could answer the query. TIA :)
Upvotes: 1
Views: 65
Reputation: 13413
as mentioned, I
and J
are sets, but the problem is that F
is a list.
try this:
I={0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150}
J={-50,-40,-30,-20,-10,0,10,20,30,40}
F={(i,j):0 for j in J for i in I}
for i in I:
for j in J:
if i+j==100:
F[(i,j)]=-j*2.782490319
else:
F[(i,j)]="NA"
print(F[(60,40)])
I changed F to be a dictionary with keys of type (int, int)
, and that's it...
Output:
-111.29961276
Upvotes: 3