find the sum of all keys in a map in python

Here is the code to find the sum of all keys in a dictionary in Python using a loop:

main.py
my_dict = {"apple": 2, "banana": 3, "orange": 4}

key_sum = 0
for key in my_dict:
    key_sum += key

print("The sum of all keys in the dictionary is:", key_sum)
162 chars
8 lines

Output:

main.py
The sum of all keys in the dictionary is: 9
44 chars
2 lines

Explanation: We first create a dictionary my_dict with some key-value pairs. We then initialize a variable key_sum to 0. We use a for loop to iterate through all the keys in the dictionary, and for each key, we add it to key_sum. Finally, we print out the total sum of all keys in the dictionary.

related categories

gistlibby LogSnag