Divide each value in a dictionary by total value in Python

avatar

Borislav Hadzhiev

Last updated: Jul 11, 2022

banner

Photo from Unsplash

Divide each value in a dictionary by total value in Python #

To divide each value in a dictionary by a total value:

  1. Use a dict comprehension to iterate over the dictionary's items.
  2. On each iteration, divide the current value by the total.
  3. The new dictionary will contain the division results.
main.py
my_dict = {'a': 1, 'b': 5, 'c': 4} # ✅ divide each dictionary value by sum of dictionary values total = sum(my_dict.values()) result = {key: value / total for key, value in my_dict.items()} # 👇️ {'a': 0.1, 'b': 0.5, 'c': 0.4} print(result) # ✅ divide each dictionary value by a number result = {key: value / 2 for key, value in my_dict.items()} print(result) # 👉️ {'a': 0.5, 'b': 2.5, 'c': 2.0}

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = {'a': 1, 'b': 5, 'c': 4} # 👇️ dict_items([('a', 1), ('b', 5), ('c', 4)]) print(my_dict.items())

We used a dict comprehension to iterate over the dictionary's items.

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary, or select a subset of key-value pairs that meet a condition.
main.py
my_dict = {'a': 1, 'b': 5, 'c': 4} # 👇️ dict_items([('a', 1), ('b', 5), ('c', 4)]) print(my_dict.items()) total = sum(my_dict.values()) result = {key: value / total for key, value in my_dict.items()}

The dict.values method returns a new view of the dictionary's values.

main.py
my_dict = {'a': 1, 'b': 5, 'c': 4} # 👇️ dict_values([1, 5, 4]) print(my_dict.values())

The sum function takes an iterable, sums its items from left to right and returns the total.

On each iteration, we divide the current key by the total and return the result.

Divide each value in a dictionary by a number in Python #

To divide each value in a dictionary by a number:

  1. Use a dict comprehension to iterate over the dictionary's items.
  2. On each iteration, divide the current value by the number and return the result.
main.py
my_dict = {'a': 1, 'b': 5, 'c': 4} result = {key: value / 2 for key, value in my_dict.items()} print(result) # 👉️ {'a': 0.5, 'b': 2.5, 'c': 2.0}

Instead of dividing by the total value, we divide by a number (2 in the example).

The new dictionary contains the same keys, but its values are the result of dividing each value of the original dictionary by 2.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.