Python Code Challenges: Dictionaries

Hi. Very much a beginner here.

Q1 my answer is:
def sum_values(my_dictionary):
sum = 0
for value in my_dictionary.values():
sum += value
return sum

Q2 my answer is:
def sum_even_keys(my_dictionary):
sum = 0
for key in my_dictionary.keys():
if key % 2 == 0:
sum += my_dictionary[key]
return sum

Can someone please explain the different syntax I have bolded. Why for one can I just write value and the other I have to write my_dictionary[key]?? I initially just had key.

Thank you very much.


the .values() method gives you the value, while the .keys() method gives you the key. When you have the value you can add this directly to the sum, while if you have the key, you will need to use the key to the get value. Which is the see in Q2

1 Like

Thank you very much.