0
Does anybody know why the dictionary values are all the last element of the second list?
Here's the code: l1=[1,2,3,4,5,6,7] l2=[1,4,9,16,25,36,49] dict2={} for i in l1: for j in l2: dict2[i]=j print(dict2.items()) I think there's a problem with the second for loop but i can't really point out what's going wrong here. If anyone could help please let me know.
5 odpowiedzi
+ 2
Yeah the second for loop keeps reassigning all the values from l2 to the same key in dict2 until it finally assigns it the last one
The second for loop is basically the equivalent of:
dict2[i]=j
Ahsen haja taaml for loop wahda kima 9al raul
walla more advanced approach kn testaalmha behya zeda is :
for i , j in zip(l1,l2):
dict2[i]=j
this way tloopi en parallèle bin l1 w l2
+ 1
This is saying
for each item in l1
Keep on assigning each item in l2
So it goes
dict[1] = 1
dict[1] = 4
dict[1] = 9
….
Until
dict[1] = 49
Then same thing for every element in l1
i think what you want is simply one for loop
for i in range( len(l1) ):
dict[ l1[i] ] = l2[i]
+ 1
FeDi BbM thank you so much for your response it really helped 😊
+ 1
Syrine Ayedi anytime
0
Raul Ramirez thank you so much for your response it really helped 😊