Replace None with empty String in a Dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Jun 15, 2022

banner

Photo from Unsplash

Replace None with empty String in a Dictionary in Python #

To replace None values with an empty string 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 the None value with an empty string.
main.py
import json employee = { 'name': None, 'address': {'country': None, 'city': 'Hamburg'}, 'age': 30, } def none_to_empty_str(items): return {k: v if v is not None else '' for k, v in items} json_str = json.dumps(employee) employee = json.loads(json_str, object_pairs_hook=none_to_empty_str) # 👇️ {'name': '', 'address': {'country': '', 'city': 'Hamburg'}, 'age': 30} print(employee)

We replaced all None values in the dictionary with empty strings.

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 none_to_empty_str(items): return {k: v if v is not None else '' 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', 'Hamburg')].

In our function, we simply check if the value is not None and return it, otherwise we return an empty string.

You could return any other value in the else block if an empty string doesn't suite your use case.

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

main.py
employee = { 'name': None, 'country': 'Austria', 'age': None, } employee = {k: v if v is not None else '' for k, v in employee.items()} # 👇️ {'name': '', 'country': 'Austria', 'age': ''} 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 an empty string.

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.