How to Remove Null/None Values From a Dictionary in Python

Given a Python dictionary, remove any term whose value is None

How to Remove Null/None Values From a Dictionary
Photo by Oliver Hale on Unsplash

Challenge

Given a Python dictionary, remove any term whose value is None

The function should accommodate nested dictionaries, which occur when the value of a term is another dictionary.

Solution

To clean the provided dictionary, each key-value pair will be examined. If the data type of the value is a dict, then the function should be recursively called. Otherwise, as long as the value is not equal to None, then it will be added to the clean dictionary, which is returned after iterating over the entire dictionary.def cleanNullTerms(d):
  clean = {}for k, v in d.items():
     if isinstance(v, dict):
        nested = cleanNullTerms(v)
        if len(nested.keys()) > 0:
           clean[k] = nested
     elif v is not None:
        clean[k] = vreturn clean

To test our function, we’ll use sample data that includes None values in both the top level as well as a nested dictionary.data = {
  "first_name": "Jonathan",
  "middle_name": None,
  "last_name": "Hsu",
  "family": {
     "mother": "Mary",
     "father": "Peter",
     "brother": "Charles",
     "sister": None
  }
}print(cleanNullTerms(data))
"""
{
 'first_name': 'Jonathan',
 'last_name': 'Hsu',
 'family': {
   'mother': 'Mary',
   'father': 'Peter',
   'brother': 'Charles'
 }
}
"""

Honorable Mention

If nested dictionaries are not a concern then a one-liner function using dictionary comprehension is sufficient. This function would perform a shallow clean, meaning None values in nested data structures would not be removed.def cleanNullTerms(d):
  return {
     k:v
     for k, v in d.items()
     if v is not None
  }

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe