0
Dictionary question.
dict = {1:15, 5:10, 4:26} sum = 0 for value in dict: sum = sum + value print(sum) Output: 10 The value of 10 has a key of 5 (not zero) so not sure how hey arrived there? Thanks for any help anyone could provide.
6 Réponses
+ 3
The for loop is iterating over the keys on the dictionary.
for value in dict:
print(value)
Output:
1
5
4
1 + 5 + 4 == 10.
+ 2
Thanks Diego and HonFu. I thought the initial number in a dictionary was called a "key"? How is one to know where to sum (add) the key in the dictionaries (the number to the left of the colon) or the actual "value" (the number to the right of the colon)?
+ 2
You just have to remember how dictionaries work.
It is not how you call the loop variable, you could have also written
for jellyfish in dict
for the same effect.
Imagine a real life dictionary, let's say it's English->Chinese.
You might want to look if a certain word is in there.
Is 'apple' in it?
Yeah, it is.
Okay, but what is the translation?
'pingguo'
So by asking if anything is 'in' a dictionary (for word in dict), you are asking for what's on the left side - the key (no matter how you name it).
And if you actually want to look up what is *stored* under that key (the 'translation'), you have to use the lookup technique.
d = {'apple': 'pingguo'}
for key in d:
print(key) # output: apple
print(d[key]) # output: pingguo
+ 2
Thanks HonFu (or should I say Xie-Xie:)). I redid the code changing some markers until it made sense. Made a copy below in case people want to try it. I re-did the code so the outcome printed my age (43).
dict = {1:15, 5:10, 4:26}
start_with = 33
for all_keys in dict:
start_with = start_with + all_keys
print(start_with)
+ 1
Yeah, I'd call that riddle a trap.
You see value, so you think, you'd get the value - but by just looping over it you get the keys instead.
for key in dict:
sum = sum + dict[key]
would actually add the values.
0
In other words, where/how should I know to loop over anything?