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

Here, we are going to learn how to print sum of key-value pairs in dictionary in Python?
Submitted by Shivang Yadav, on March 25, 2021

A 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.

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.

Python Dictionary Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.