+ 3
It won't work, why?
5 Respuestas
+ 3
It's working. However, it's a loop so the variable 'p' is only storing the last value stored in it. Your print statement is after the loop, so your only output is the last value stored to variable 'p'.
If you place your print statement inside of the loop, you'll see that it's actually iterating through ALL of the values. In your loop statement, the two variables immediately after FOR is storing the KEY and the VALUE for each iteration of the loop. I'm assuming you want it to only print the value for "wws" since you're storing that value in your variable 'k'.
:::: EXAMPLE :::::
from collections import OrderedDict
k="wws"
dic = OrderedDict ( [ ("wws", (1,772,3) ) , ("ffff", (6,5,8)) ] )
for key, value in dic.items():
if k == key:
print(value)
print(key)
https://code.sololearn.com/c87IALG5EER3/#py
+ 2
@Jakob
Ooooooo...I finally understand it ! Your explanation is AWESOME! Thanks a lot for explanation and for the code you wrote! Really thank you, now I can relax.
+ 2
@Sylar
Thank you 😃 I appreciate your answer! It does help.
+ 2
@Voja
It's my pleasure, Voja! Best of luck to you.
+ 1
Because you assign last value to p. Assignment override previous value.
Your code:
dic = OrderedDict ( [ ("wws", (1,772,3) ) , ("ffff", (6,5,8)) ] )
When using 'for' loop, it loop 2 times, because dic contain 2 dictionary [i.e ("wws", (1,772,3)) and ("ffff", (6,5,8)) ].
So first time of for loop, p = (1,772,3)
Second time of for loop, p = (6,5,8)
In second time, it override previous p value. So print() only output 6,5,8.
To get both values, you need to store in some container like list.
Eg.
myList = []
for t,p in dic.items:
myList.append(p)
print(myList)
Extra: To print only specific value of your choice, use list index. Eg. print(myList[0]) >> (1,772,3) #print output
Hope it helps :)