Python program to find the sum of all items in a dictionary

PythonServer Side ProgrammingProgramming

In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given a dictionary, and we need to print the 3 highest value in a dictionary.

Three approaches to the problem statement are given below:

Approach 1: Calculating sum from the dictionary iterable

Example

 Live Demo

# sum function
def Sum(myDict):
   sum_ = 0
   for i in myDict:
      sum_ = sum_ + myDict[i]
   return sum_
# Driver Function
dict = {'T': 1, 'U':2, 'T':3, 'O':4, 'R':5}
print("Sum of dictionary values :", Sum(dict))

Output

Sum of dictionary values : 14

Approach 2: Calculating the sum from the dictionary.values() iterable

Example

 Live Demo

# sum function
def Sum(dict):
   sum_ = 0
   for i in dict.values():
      sum_ = sum_ + i
   return sum_
# Driver Function
dict = {'T': 1, 'U':2, 'T':3, 'O':4, 'R':5}
print("Sum of dictionary values :", Sum(dict))

Output

Sum of dictionary values : 14

Approach 3: Calculating the sum from the dictionary.values() iterable

Example

 Live Demo

# sum function
def Sum(dict):
   sum_ = 0
   for i in dict.keys():
      sum_ = sum_ + dict[i]
   return sum_
# Driver Function
dict = {'T': 1, 'U':2, 'T':3, 'O':4, 'R':5}
print("Sum of dictionary values :", Sum(dict))

Output

Sum of dictionary values : 14

Conclusion

In this article, we have learned how we can find the highest 3 values in a dictionary

raja
Published on 24-Dec-2019 05:09:42
Advertisements