Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.
Dictionary is a collection in python which is used to store data as Key:value pair.
Example:
dict = { "python" : 1, "C++" : 3, "javaScript" : 2 }
Sum of all items of the dictionary
Here, we have a dictionary that has integer values as a value in the key:value pair. We need to find the sum of all items (value) of the dictionary.
Input:
dict = {"python" : 1, "C++" : 3, "javaScript" : 2 }
Output:
sum of all items of the dictionary : 6
We simply need to add all the values of the dictionary and print the sum. This can be done in python in more than one way, we can either iterate through the collection or we can use built-in methods to find the sum.
Method 1: Using the sum() method
Python provides a built-in sum() method to find the sum of all items of an iterable. And we can also pass the values of a dictionary in the sum method to find the sum. For this we will use another built-in python method values().
Syntax:
Program to find the sum of all items of the dictionary using sum() method
Output:
Method 2: By iterating over dictionary and adding values
We can alternatively iterate over the dictionary and add each value to a sum variable and after completion print that variable.
Algorithm:
For iteration also, we have multiple ways, we can either iteratie over the whole dictionary and access the values using their keys. Or we can directly iterate over the values and add them.
Program to find the sum of all items of the dictionary using for loop of dictionary
Output:
Program to find the sum of all items of the dictionary using for loop of values of dictionary
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer