Python Code Challenges: Dictionaries (Even Keys)


I am struggling with my output for this challenge:

Create a function called sum_even_keys that takes a dictionary named my_dictionary , with all integer keys and values, as a parameter. This function should return the sum of the values of all even keys.

I believe I have the theory behind my answer down, but I keep getting the incorrect output of 0 and 1, instead of the expected 2 and 6. Here is my code:

def sum_even_keys(my_dictionary):
  counter = 0
  for i in my_dictionary.keys():
    if (i % 2 == 0):
      counter += my_dictionary[i]
    return counter

print(sum_even_keys({1:5, 2:2, 3:3}))
# should print 2
print(sum_even_keys({10:1, 100:2, 1000:3}))
# should print 6```

Could anyone shed insight into why this is? I copied the solution and it outputted correctly. 

Thank you.

Double check your indentation on that return statement.


Why do you have it indented to the inner loop level?

1 Like

Thanks! That did the trick. I’ll pay more attention to my indentations.