Remove None values from a list in Python

avatar

Borislav Hadzhiev

Last updated: Jun 15, 2022

banner

Photo from Unsplash

Remove None values from a Dictionary in Python #

Use a dict comprehension to remove None values from a dictionary in Python. The dict comprehension will get passed each key-value pair in the dictionary where we can check if the value is not None before including it in the final result.

main.py
my_dict = { 'name': 'Alice', 'age': None, 'country': None, 'language': 'German' } new_dict = { key: value for key, value in my_dict.items() if value is not None } # 👇️ {'name': 'Alice', 'language': 'German'} print(new_dict)

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.

Note that this approach doesn't remove the None values from the dictionary, it creates a new dictionary that doesn't contain any None values.

An alternative approach is to use a for loop.

To remove None values from a dictionary:

  1. Use a for loop to iterate over the dictionary's items.
  2. On each iteration, check if the value is None.
  3. If the value is None, delete the corresponding key.
main.py
my_dict = { 'name': 'Alice', 'age': None, 'country': None, 'language': 'German', } for key, value in my_dict.copy().items(): if value is None: del my_dict[key] # 👇️ {'name': 'Alice', 'language': 'German'} print(my_dict)

We created a copy of the dictionary because it's not allowed to change the size of a dictionary while iterating over it.

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

main.py
my_dict = {'id': 1, 'name': 'Alice'} print(my_dict.items()) # 👉️ dict_items([('id', 1), ('name', 'Alice')])

On each iteration, we check if the value is None, and if it is, we delete the corresponding key.

This approach mutates the original dictionary.

You can also add not-None key-value pairs to a new dictionary instead of mutating the original one.

main.py
my_dict = { 'name': 'Alice', 'age': None, 'country': None, 'language': 'German' } new_dict = {} for key, value in my_dict.copy().items(): if value is not None: new_dict[key] = value # 👇️ {'name': 'Alice', 'language': 'German'} print(new_dict)

On each iteration, we check if the value is not None, and if it isn't, we add the key-value pair to a new dictionary.

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.