Skip to content
Related Articles

Related Articles

Python Program to print sum of all key value pairs in a Dictionary

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 22 Mar, 2021
Improve Article
Save Article

Given a dictionary arr consisting of N items, where key and value are both of integer type, the task is to find the sum of all key value pairs in the dictionary.

Examples:

Input: arr = {1: 10, 2: 20, 3: 30}
Output: 11 22 33
Explanation: 
Sum of key and value of the first item in the dictionary = 1 + 10 = 11.
Sum of key and value of the second item in the dictionary = 2 + 20 = 22.
Sum of key and value of the third item in the dictionary = 3 + 30 = 33.

Input: arr = {10 : -5, 5 : -10, 100 : -50}
Output: 5 -5 50

Approach using dictionary traversal technique: The idea is to traverse through the keys of dictionary using for loop. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

Python3




# Python3 implementation of
# the above approach
  
# Function to print the list containing
# the sum of key and value pairs of
# each item of a dictionary
def FindSum(arr):
  
    # Stores the list containing the
    # sum of keys and values of each item
    l = []
  
    # Traverse the dictionary
    for i in arr:
  
        l.append(i + arr[i])
  
    # Print the list l
    print(*l)
  
# Driver Code
  
arr = {1: 10, 2: 20, 3: 30}
  
FindSum(arr)

Output:

11 22 33

Time Complexity: O(N)
Auxiliary Space: O(N)

Approach using keys() Method: An alternate approach to solve the problem is to use keys() method. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

Python3




# Python3 implementation of the above approach
  
# Function to print the list
# containing the sum of key and
# value pairs from a dictionary
def FindSum(arr):
  
    # Stores the list containing the
    # sum of keys and values of each item
    l = []
  
    # Traverse the list of keys of arr
    for i in arr.keys():
  
        l.append(i + arr[i])
          
    # Print the list l
    print(*l)
  
# Driver Code
  
arr = {1: 10, 2: 20, 3: 30}
  
FindSum(arr)

Output:

11 22 33

Time Complexity: O(N)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!