Q:

Python program to print sum of key-value pairs in dictionary

belongs to collection: Python Dictionary Programs

0

dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas. 

Key is an identifier value that is unique and is required for the dictionary to function. Key is provided in the dictionary to make it more optimized.

The value is the related value given for the key.

We need to add the keys and values for each pair in the dictionary and print their sum.

Example:

dictionary = [5:3, 8:2, 9:4]
Output: 8, 10, 13

One method to find the sum is to iterate over the dictionary and find the sum of each key-value pair. Then store the sum into a list and print the list.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to print the sum of key-value pairs in dictionary

# Program to print sum of key-value 
# pairs in dictionary

dictionary = {1: 10, 2: 20, 3: 30}
sumList = []

# Traverse the dictionary
for key in dictionary:
	sumList.append(key + dictionary[key])

# Print the list
print("Key-value sum =",*sumList)

Output:

Key-value sum = 11 22 33

Explanation:

In the above code, we have created a dictionary named dictionary to store some key-value pairs. Then we traverse the dictionary using a for-in loop with a key as an element. Then we have added key and values attached to it and store in a list sumList. At last, we have printed the list.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Dictionary Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to replace dictionary value for the... >>
<< Python program to extract unique values from the d...