How to Remove the None values from a Dictionary in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
5 min

banner

# Table of Contents

  1. Remove None values from a Dictionary in Python
  2. Remove None values from a Dictionary using a for loop
  3. Adding the not-None key-value pairs to a new dictionary
  4. Remove the None values from a nested Dictionary in Python
  5. Replace None values in a Dictionary in Python
  6. Replace None values in a Dictionary using dict comprehension

# 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': 'Bobby Hadz', 'age': None, 'country': None, 'language': 'German' } new_dict = { key: value for key, value in my_dict.items() if value is not None } # ๐Ÿ‘‡๏ธ {'name': 'Bobby Hadz', 'language': 'German'} print(new_dict)

remove none values from dictionary

The code for this article is available on GitHub

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 in place, it creates a new dictionary that doesn't contain any None values.

An alternative approach is to use a for loop.

# Remove None values from a Dictionary using a for loop

This is a three-step process:

  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': 'Bobby Hadz', 'age': None, 'country': None, 'language': 'German', } for key, value in my_dict.copy().items(): if value is None: del my_dict[key] # ๐Ÿ‘‡๏ธ {'name': 'Bobby Hadz', 'language': 'German'} print(my_dict)

remove none values from dictionary using for loop

The code for this article is available on GitHub

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': 'Bobby Hadz'} print(my_dict.items()) # ๐Ÿ‘‰๏ธ dict_items([('id', 1), ('name', 'Bobby Hadz')])

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.

# Adding the not-None key-value pairs to a new 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': 'Bobby Hadz', 'age': None, 'country': None, 'language': 'German' } new_dict = {} for key, value in my_dict.items(): if value is not None: new_dict[key] = value # ๐Ÿ‘‡๏ธ {'name': 'Bobby Hadz', 'language': 'German'} print(new_dict)

adding not none key value pairs to new dictionary

The code for this article is available on GitHub

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.

# Remove the None values from a nested Dictionary in Python

If you need to remove the None values from a nested dictionary, use a recursive function.

main.py
def remove_none_from_dict(dictionary): for key, value in list(dictionary.items()): if value is None: del dictionary[key] elif isinstance(value, dict): remove_none_from_dict(value) elif isinstance(value, list): for item in value: if isinstance(item, dict): remove_none_from_dict(item) return dictionary my_dict = { 'name': 'Bobby Hadz', 'age': None, 'country': None, 'language': 'German', 'address': { 'country': None, 'city': 'Example' } } # {'name': 'Bobby Hadz', 'language': 'German', # 'address': {'city': 'Example'}} print(remove_none_from_dict(my_dict))
The code for this article is available on GitHub

The function uses the dict.items() method to iterate over the supplied dictionary.

On each iteration, we check if the current value is None.

main.py
if value is None: del dictionary[key]

If the condition is met, we delete the key from the dictionary.

The first elif statement checks if the value is a dictionary.

main.py
elif isinstance(value, dict): remove_none_from_dict(value)

If the value is a nested dictionary, we pass it to the function, so it removes the direct None values.

The second elif statement checks if the value is a list.

main.py
elif isinstance(value, list): for item in value: if isinstance(item, dict): remove_none_from_dict(item)

If the value is a list, then it might be a list of dictionaries, so we iterate over the list.

On each iteration, we check if the current item is a dictionary.

If the condition is met, we call the function with the dictionary, so it can remove the direct None values.

# Replace None values in a Dictionary in Python

To replace the None values in a dictionary:

  1. Use the object_pairs_hook keyword argument of the json.loads() method.
  2. Check if each value the object_pairs_hook function gets called with is None.
  3. If it is, replace None with the specified replacement value.
main.py
import json person = { 'name': None, 'address': {'country': None, 'city': None, 'street': 'abc 123'}, 'language': 'German', } def replace_none_in_dict(items): replacement = '' return {k: v if v is not None else replacement for k, v in items} json_str = json.dumps(person) person = json.loads(json_str, object_pairs_hook=replace_none_in_dict) # ๐Ÿ‘‡๏ธ {'name': '', 'address': {'country': '', 'city': '', 'street': 'abc 123'}, 'language': 'German'} print(person)
The code for this article is available on GitHub
You can update the replacement variable in the replace_none_in_dict function to change the replacement value.

The json module makes things a little more straightforward if you have nested objects that may have None values.

The json.dumps() method converts a Python object to a JSON formatted string.

The json.loads() method parses a JSON string into a native Python object.

We passed the object_pairs_hook keyword argument to the json.loads() method and set it to a function.

main.py
def replace_none_in_dict(items): replacement = '' return {k: v if v is not None else replacement for k, v in items}

The function is going to get called with a list of key-value pair tuples, e.g. [('country', None), ('city', None), ('street', 'abc 123')].

In our function, we simply check if the value is not None and return it, otherwise, we return a replacement value.

# Replace None values in a Dictionary using dict comprehension

If your dictionary doesn't contain nested objects, use a dict comprehension.

main.py
person = { 'name': None, 'address': None, 'language': 'German', 'country': 'Germany', } # ๐Ÿ‘‡๏ธ change this if you need to update the replacement value replacement = '' employee = { key: value if value is not None else replacement for key, value in person.items() } # ๐Ÿ‘‡๏ธ {'name': '', 'address': '', 'language': 'German', 'country': 'Germany'} print(employee)
The code for this article is available on GitHub

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')])

In our dict comprehension, we check if each value isn't None and return it, otherwise, we return a replacement.

Note that this approach wouldn't work if your dictionary has nested dictionaries that have None values. If that's the case, use the previous approach.

I've also written an article on how to remove the None values from a list.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev