Replace None values in a Dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Jun 15, 2022

banner

Photo from Unsplash

Replace None values in a Dictionary in Python #

To replace None values in a dictionary in Python:

  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 specific 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)
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 straight forward 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.

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 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 is not 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 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.