Sum of values of elements in a Dictionary in Python
A dictionary is a collection of elements with key-value pairs. The values in the elements are accessed with the keys of that element. So let’s start learning: how to find the sum of values of elements in a dictionary in Python. One can gain knowledge on the functions and methods of a dictionary by typing
>> help(dict)
in the Python IDLE.
Using this program, we will add up all the integral values of the elements in a dictionary. This can be done either by using the math function or normally accessing each value using a loop.
Learn: Creation, Addition, Removal and Modification of Dictionary in Python
Python program to find the sum of values of elements in a dictionary
def SUM(dict): k=dict.values() sumd=0 for i in k: sumd=sumd+i print(sumd) diction1={'A':1,'B':2,'C':3,'D':4,'E':5} SUM(diction1)
OUTPUT:
15
CODE EXPLANATION:
We are considering a parameter dict which would later, during function call be replaced by a global variable to which a dictionary is assigned. For eg: In the above code, we use a variable diction1 and then replace the parameter by diction1 while calling SUM(). A user-defined function named SUM is used to obtain the desired output.
- As a first step, we used a variable k allocated in memory and assigned a list to it. You must be wondering, LIST? WHERE DID THAT COME FROM?
- The dict.values() method of a dictionary forms a list of the values of the elements in the dictionary. For eg : if there is a dictionary d={‘A’:1,’B’:2,’C’:3,’D’:4,’E’:5} then the method d.values() generates a list of the values of the elements.
- A variable sumd is allocated to a memory space. It is assigned integer 0.
- Using a for loop, one can traverse the list allocated to variable k.
- Then every single element of the list is added to the variable called sumd.
- The variable sumd calculates the sum of the values of the dictionary elements is then printed.
Leave a Reply