+ 1
_sum = o
a = {0:1, 1:2} _sum = o for b in a: _sum += b print(_sum+b) Output: 2 What do they mean by "for b in a"? A is a dictionary, but the keys are 0 and 1? Any idea how to solve this one?
3 ответов
+ 5
With 'in' you ask for the key. (The value you get with a[key].)
So b is first 0, then 1.
After the loop, b stays what it was in the last loop.
Can you figure it out now?
+ 1
Thanks HonFu! It's clearer, but some points still confused on:
-for b in a: _sum += b
#Is "b" always going to be the key of a dictionary? Where was that part defined?
+ 1
It is defined in the datatype dict.
Whenever you just walk through a dict without 'looking up' its values, it is like if you browse through your Spanish dictionary and only read the left side.
So yeah, however you call the for variable...
for key in a
for jellyfish in a # heck, even
for value in a
... you will always get the key.
You could try to turn your dictionary into a list by writing...
a = list(a)
... and it would contain only the keys.
You need to specifically use the 'look that word up' function of your dict to get through to the value:
print(a[key])
So the code just sums up the keys, which leads to 1, and prints it out adding b again, that still stores the last key (1) - so the result is 2.
Btw, if you wanted to sum up the values instead of the keys, you'd just have to write:
_sum += a[b]
... instead of...
_sum += b