Calculating With Dictionaries in Python

In this tutorial, we will learn how to perform various calculations (e.g., minimum value, maximum value, sorting, etc.) and operations in dictionary data. When we have a dictionary and we want to find the minimum, maximum value and sorted dictionaries then this tutorial becomes helpful for you. Here we see easy method to do the following operations.

Dictionary calculations in Python

To perform useful calculations on the dictionary contents, we can use zip() function. It will let us invert the keys and values. Basically here we use the zip() method to exchange the key and value of the dictionary. For example, we have a dictionary:

prices = {   'a': 45.23,   'b': 612.78,   'c': 205.55,   'd': 37.20,   'e': 10.75 }

Noe we find the minimum and maximum price and stock name as:

prices = { 'a': 45.23, 'b': 612.78, 'c': 205.55, 'd': 37.20, 'e': 10.75 } 
min_price = min(zip(prices.values(), prices.keys()))
max_price = max(zip(prices.values(), prices.keys()))
print("min_price :",min_price)
print("min_price :",min_price)


min_price : (10.75, 'e')
max_price : (612.78, 'b')

Similarly, to rank the data or the key and values of the dictionary we use zip() with sorted(), as in the following example:

prices = { 'a': 45.23, 'b': 612.78, 'c': 205.55, 'd': 37.20, 'e': 10.75 }
prices_sorted = sorted(zip(prices.values(), prices.keys()))
print("sorted or arranged data :",prices_sorted)

Output :

sorted or arranged data : [(10.75, 'e'), (37.2, 'd'), (45.23, 'a'), (205.55, 'c'), (612.78, 'b')]

Hence, we can do the calculations by using the appropriate function on the zip() method.

You can also go through the following links for more information about dictionary:

Sum of values of elements in a Dictionary in Python

Sort A Dictionary By Key In Python

Leave a Reply

Your email address will not be published. Required fields are marked *