Last updated: Apr 8, 2024
Reading timeยท5 min
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.
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)
Dict comprehensions are very similar to list comprehensions.
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.
for
loopThis is a three-step process:
for
loop to iterate over the dictionary's items.None
.None
, delete the corresponding key.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)
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).
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.
You can also add not None
key-value pairs to a new dictionary instead of
mutating the original one.
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)
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.
If you need to remove the None
values from a nested dictionary, use a
recursive function.
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 function uses the dict.items()
method to iterate over the supplied
dictionary.
On each iteration, we check if the current value is None
.
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.
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.
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.
To replace the None values in a dictionary:
object_pairs_hook
keyword argument of the json.loads()
method.object_pairs_hook
function gets called with is
None
.None
with the specified replacement value.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)
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.
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.
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).
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.
You can learn more about the related topics by checking out the following tutorials: