Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Add a key value pair to Dictionary in Python
Next article icon

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

Last Updated : 14 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Method 1:

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:

  • Initialize a list, say l, to store the result.
  • Traverse the dictionary arr and then append i + arr[i] into the list l.
  • After completing the above steps, print the list l as the required answer.

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)

Method 2:

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

  • Initialize a list, say l, to store the result.
  • Traverse through the list of keys of dictionary arr and then append.
  • After completing the above steps print the list l as answer.

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)

Method 3 : Using keys(),values() and for loop

Python3




# Python3 implementation of the above approach
arr = {1: 10, 2: 20, 3: 30}
x = list(arr.keys())
y = list(arr.values())
res = []
for i in range(0, len(x)):
    res.append(x[i]+y[i])
for i in res:
    print(i, end=" ")
 
 
Output
11 22 33 

Time Complexity: O(n), where n is the number of keys in the dictionary.
Auxiliary Space: O(n), as two arrays of size n are created to store the keys and values of the dictionary.

Method 4: Using zip() and a list comprehension

This approach uses the python built-in function zip() to extract the keys and values of the dictionary and combines them in a tuple. Using a list comprehension, we add the key and value of each item in the dictionary. The final result is the sum of all key-value pairs in the dictionary. The time complexity of this approach is O(n) and the space complexity is O(n) as we are creating a new list to store the sum of each key-value pair.

Python3




def find_sum(arr):
    # Using zip to get the keys and values of the dictionary
    keys, values = zip(*arr.items())
    # Using list comprehension to add the key and value of each item
    return [k+v for k,v in zip(keys, values)]
 
arr = {1: 10, 2: 20, 3: 30}
print(find_sum(arr))
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
[11, 22, 33]

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

Method 5: Using a simple for loop to iterate over the keys and values of the dictionary

Directly iterate over the items of the dictionary using the items() method, which returns a sequence of (key, value) pairs. We then add each key and value together and append the result to a list. Finally, we return the list of results.

Python3




def find_sum(arr):
    # Create an empty list to store the result
    result = []
     
    # Iterate over the keys and values of the dictionary
    for key, value in arr.items():
        # Add the key and value and append the result to the list
        result.append(key + value)
     
    # Return the list of results
    return result
 
# Example usage:
arr = {1: 10, 2: 20, 3: 30}
print(find_sum(arr))
# Output: [11, 22, 33]
 
 
Output
[11, 22, 33]

Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary space: O(n), since we are creating a list to store the result.

Method 6:Using itertools strmap()

Algorithm:

  1. Import the itertools.starmap() function
  2. Define the find_sum() function that takes a dictionary arr as input
  3. Use the starmap() function with a lambda function to add the key and value of each item in the dictionary arr
  4. Convert the resulting iterable of sums to a list and return the list

Python3




from itertools import starmap
 
def find_sum(arr):
    return list(starmap(lambda key, value: key+value, arr.items()))
 
# example usage
arr = {1: 10, 2: 20, 3: 30}
result = find_sum(arr)
print(result)  # Output: [11, 22, 33]
#This code is contributed by Vinay pinjala.
 
 
Output
[11, 22, 33]

Time complexity:
The time complexity of the find_sum() function is O(n), where n is the number of items in the dictionary arr. The starmap() function iterates over each item in the dictionary and applies a lambda function to calculate the sum of the key and value for each item. The time complexity of the lambda function is constant, so it does not affect the overall time complexity of the function.

Auxiliary Space:

Auxiliary Space of the code is O(1),because we don’t storing list.



Next Article
Add a key value pair to Dictionary in Python

T

thotasravya28
Improve
Article Tags :
  • DSA
  • Mathematical
  • Python Programs
  • Python dictionary-programs
Practice Tags :
  • Mathematical

Similar Reads

  • Python Program to find XOR of all the key value pairs in a Dictionary
    Given a dictionary in python, write a program to find the XOR of all the key-value pairs in the dictionary and return in the form of an array. Note: All the keys and values in the dictionary are integers. Examples: Input : dic={1:3, 4:5, 6:7, 3 :8}Output : [2, 1, 1, 11]Explanation: XOR of all the ke
    3 min read
  • Add a key value pair to Dictionary in Python
    The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key. For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'f
    3 min read
  • Python program to find the highest 3 values in a dictionary
    Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Examples: Input : my_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69} Output :
    5 min read
  • Python program to find the sum of all items in a dictionary
    The task of finding the sum of all items in a dictionary in Python involves calculating the total of all values stored in a dictionary. For example, given a dictionary {'a': 100, 'b': 200, 'c': 300}, the sum of values would be 100 + 200 + 300 = 600. Using sum()This is the simplest and fastest method
    3 min read
  • Python | Value summation of key in dictionary
    Many operations such as grouping and conversions are possible using Python dictionaries. But sometimes, we can also have a problem in which we need to perform the aggregation of values of key in dictionary list. This task is common in day-day programming. Let's discuss certain ways in which this tas
    6 min read
  • Python - Key Value list pairings in Dictionary
    Sometimes, while working with Python dictionaries, we can have problems in which we need to pair all the keys with all values to form a dictionary with all possible pairings. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be
    7 min read
  • Python - List of dictionaries all values Summation
    Given a list of dictionaries, extract all the values summation. Input : test_list = [{"Apple" : 2, "Mango" : 2, "Grapes" : 2}, {"Apple" : 2, "Mango" : 2, "Grapes" : 2}] Output : 12 Explanation : 2 + 2 +...(6-times) = 12, sum of all values. Input : test_list = [{"Apple" : 3, "Mango" : 2, "Grapes" : 2
    5 min read
  • Python program to multiply all the items in a dictionary
    Python program to illustrate multiplying all the items in a dictionary could be done by creating a dictionary that will store all the key-value pairs, multiplying the value of all the keys, and storing it in a variable. Example: Input: dict = {'value1':5, 'value2':4, 'value3':3, 'value4':2, 'value5'
    2 min read
  • Python Print Dictionary Keys and Values
    When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values. Example: Using print() Method [GFGTABS] Python my_dict = {'a': 1, 'b'
    2 min read
  • Python - Mapping Key Values to Dictionary
    We are given two list and we need to map key to values of another list so that it becomes dictionary. For example, we are given two list k = ['a', 'b', 'c'] and v = [1, 2, 3] we need to map the keys of list k to the values of list v so that the resultant output should be {'a': 1, 'b': 2, 'c': 3}. Us
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences