Even Keys || Python

Even Keys || Python

Even Keys

Next, we are going to do something similar, but we are going to use the keys in order to retrieve the values. Additionally, we are going to only look at every even key within the dictionary. Here are the steps:

  1. Define the function to accept one parameter for our dictionary
  2. Create a variable to keep track of our sum
  3. Loop through every key in the dictionary
  4. Inside the loop, if the key is even, add the value from the even key
  5. After the loop, return the sum

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.

No alt text provided for this image

Similar to the previous problem, we are iterating through our dictionary, except this time we are iterating through the keys instead of the values. In order to get the keys we use the?keys()?function and to get the value of a key we can use brackets. To test if the key is even we use the modulus operator and test if the remainder is 0 when dividing by 2.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了