Generally, you'll create a new dict constructed from filtering the old one. dictionary comprehensions are great for this sort of thing:

{k: v for k, v in original.items() if v is not None}

If you must update the original dict, you can do it like this ...

filtered = {k: v for k, v in original.items() if v is not None}
original.clear()
original.update(filtered)

This is probably the most "clean" way to remove them in-place that I can think of (it isn't safe to modify a dict while you're iterating over it)


Use original.iteritems() on python2.x

Answer from mgilson on Stack Overflow
Top answer
1 of 8
214

Generally, you'll create a new dict constructed from filtering the old one. dictionary comprehensions are great for this sort of thing:

{k: v for k, v in original.items() if v is not None}

If you must update the original dict, you can do it like this ...

filtered = {k: v for k, v in original.items() if v is not None}
original.clear()
original.update(filtered)

This is probably the most "clean" way to remove them in-place that I can think of (it isn't safe to modify a dict while you're iterating over it)


Use original.iteritems() on python2.x

2 of 8
21

if you need to delete None values recursively, better to use this one:

def delete_none(_dict):
    """Delete None values recursively from all of the dictionaries"""
    for key, value in list(_dict.items()):
        if isinstance(value, dict):
            delete_none(value)
        elif value is None:
            del _dict[key]
        elif isinstance(value, list):
            for v_i in value:
                if isinstance(v_i, dict):
                    delete_none(v_i)

    return _dict

with advice of @dave-cz, there was added functionality to support values in list type.

@mandragor added additional if statement to allow dictionaries which contain simple lists.

Here's also solution if you need to remove all of the None values from dictionaries, lists, tuple, sets:

def delete_none(_dict):
    """Delete None values recursively from all of the dictionaries, tuples, lists, sets"""
    if isinstance(_dict, dict):
        for key, value in list(_dict.items()):
            if isinstance(value, (list, dict, tuple, set)):
                _dict[key] = delete_none(value)
            elif value is None or key is None:
                del _dict[key]

    elif isinstance(_dict, (list, set, tuple)):
        _dict = type(_dict)(delete_none(item) for item in _dict if item is not None)

    return _dict

The result is:

# passed:
a = {
    "a": 12, "b": 34, "c": None,
    "k": {"d": 34, "t": None, "m": [{"k": 23, "t": None},[None, 1, 2, 3],{1, 2, None}], None: 123}
}

# returned:
a = {
    "a": 12, "b": 34, 
    "k": {"d": 34, "m": [{"k": 23}, [1, 2, 3], {1, 2}]}
}
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ python-remove-none-from-dict
How to Remove the None values from a Dictionary in Python | bobbyhadz
April 8, 2024 - 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.
Discussions

python - How I can get rid of None values in dictionary? - Stack Overflow
This question is similar to: Proper way to remove keys in dictionary with None values in Python. More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Removing key/value pairs in list of dicts - Code Review Stack Exchange
I have a list of dicts that all have the same keys. If a key's value is None in all dicts then I want to remove them (A solution that creates a new dict is fine as well). I'm concerned about my B... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
September 7, 2017
mongodb - remove none value on a dict in python won't work - Stack Overflow
I want to modify my mongo DB collection data with removing the None value. I have a nested dict. I did a query to get all the db on my db: doc = db.events.find() for document in doc: print More on stackoverflow.com
๐ŸŒ stackoverflow.com
Delete None values from Python dict - Stack Overflow
Newbie to Python, so this may seem silly. ... I need to update my defaults with the values that exist in user. But only for those that have a value not equal to None. So I need to get back a new dict: More on stackoverflow.com
๐ŸŒ stackoverflow.com
August 26, 2009
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ python-program-to-remove-null-values-from-a-dictionary
Python program to remove null values from a dictionary
March 27, 2026 - Dictionary comprehension provides a more elegant and Pythonic solution ? data = {"key1": 2, "key2": None, "key3": 5, "key4": "abc", "key5": None} filtered_dict = {k: v for k, v in data.items() if v is not None} print("Filtered dictionary:", filtered_dict) Filtered dictionary: {'key1': 2, 'key3': 5, 'key4': 'abc'} You can extend the condition to remove other "falsy" values like empty strings or zero ?
๐ŸŒ
CodeSpeedy
codespeedy.com โ€บ home โ€บ how to remove none values from a dictionary in python
How to remove None values from a dictionary in Python - CodeSpeedy
July 11, 2020 - #Create a List keys = ["Name", ... remove keys with Value as None for key, value in dict(d).items(): if value is None: del d[key] print(d)...
๐ŸŒ
Better Programming
betterprogramming.pub โ€บ how-to-remove-null-none-values-from-a-dictionary-in-python-1bedf1aab5e4
How to Remove Null/None Values From a Dictionary in Python | by Jonathan Hsu | Better Programming
October 11, 2019 - 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] = v return 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.
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ 5 best ways to remove null values from a python dictionary
5 Best Ways to Remove Null Values from a Python Dictionary - Be on the Right Side of Change
February 26, 2024 - This snippet uses filter() to keep only the items that do not have a None value, effectively skipping the ones that do. The resulting iterator is then converted back into a dictionary. You can use a combination of pop() method with a for-loop to explicitly remove null values based on a conditional check inside the loop.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-removing-nested-none-dictionaries
Python - Removing Nested None Dictionaries - GeeksforGeeks
April 27, 2023 - 1. Iterate through each key-value pair in the dictionary. 2. If the value is a dictionary, call the remove_nested_none_dicts function recursively on the value. 3 If the value is None or an empty dictionary, remove the key from the dictionary.
Find elsewhere
๐ŸŒ
CSEstack
csestack.org โ€บ home โ€บ how to remove all zero/none/null from dictionary in python?
How to Remove All Zero/None/Null from Dictionary in Python?
July 11, 2020 - There is also the easiest way to do this using the python compression technique. Here is simple code spinet we can use it to filter out the the dictionary items having values zero. ... You can run the complete program here that removes all 0 from the dictionary in Python.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ filter-non-none-dictionary-keys-in-python
Filter Non-None dictionary keys in Python
Then create the empty dictionary in the variable filter_dict that will store only integer value of the key. Now use the for loop that iterates the key and value of the dictionary using method items(). Using an if-statement it will check if the value is found to be none then it will auto-removing the key : value from the dictionary.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-remove-empty-value-types-in-dictionaries-list
Python - Remove empty value types in dictionaries list - GeeksforGeeks
April 25, 2023 - using list comprehension, but instead of using a nested dictionary comprehension, we use a single dictionary comprehension inside the outer list comprehension. The if statement is used to filter out None values.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-filter-non-none-dictionary-keys
Python - Filter Non-None dictionary Keys - GeeksforGeeks
May 11, 2023 - Use filter() function with a lambda function to filter out the None values from the mapped list. Convert the filtered list to a list using list() function. Below is the implementation of the above approach: ... # Python3 code to demonstrate ...
๐ŸŒ
Medium
medium.com โ€บ @sahasuraj420 โ€บ remove-null-none-and-empty-strings-from-an-n-sub-level-dictionary-92266dba6a
Remove Null, None, and Empty Strings from an n-sub level dictionary | by Suraj Saha | Medium
April 27, 2022 - The first one is if the value of a key is a normal value which is neither None nor empty string, in that case, we are going to add it to our new dictionary. Second one is if a value is dictionary itself, in that case we are going to make a recursive call to remove all none, null or empty spaces from that dictionary.
Top answer
1 of 1
6

Any solution will have to read the values associated to each key of each dictionary; so you won't be able to drop under \$\mathcal{O}(n\times{}m)\$ where \$m\$ is the length of each dictionary. This is pretty much what you are doing, but the if k not in keep_keys call slows things a bit as it is \$\mathcal{O}(m)\$ when it could be \$\mathcal{O}(1)\$ by using a set or a dictionary.

If you change the keep_keys list into a set you simplify the logic a bit: as soon as you find a key whose value is not None you can add it into the set.

dicts = [{'a': 1, 'b': None, 'c': 4}, {'a': 2, 'b': None, 'c': 3}, {'a': None, 'b': None, 'c': 3}]
expected = [{'a': 1, 'c': 4}, {'a': 2, 'c': 3}, {'a': None, 'c': 3}]

keep_keys = set()

for d in dicts:
    for key, value in d.items():
        if value is not None:
            keep_keys.add(key)

remove_keys = set(d) - keep_keys

for d in dicts:
    for k in remove_keys:
        del d[k]

print dicts == expected

This code, as your original one, assume that there is at least one item in dicts; otherwise set(d) will generate an exception as the variable d is not defined yet.


But this code mixes the actual logic with some tests. You should wrap it in a function to ease reusability and put the testing code under an if __name__ == '__main__': clause:

def filter_nones(dictionaries):
    if not dictionaries:
        return

    keep_keys = set()

    for dict_ in dictionaries:
        for key, value in dict_.iteritems():
            if value is not None:
                keep_keys.add(key)

    remove_keys = set(dict_) - keep_keys

    for dict_ in dictionaries:
        for key in remove_keys:
            del dict_[key]


if __name__ == '__main__':
    dicts = [
            {'a': 1, 'b': None, 'c': 4},
            {'a': 2, 'b': None, 'c': 3},
            {'a': None, 'b': None, 'c': 3},
    ]
    expected = [
            {'a': 1, 'c': 4},
            {'a': 2, 'c': 3},
            {'a': None, 'c': 3},
    ]

    filter_nones(dicts)
    print dicts == expected
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 38568687 โ€บ remove-none-value-on-a-dict-in-python-wont-work
mongodb - remove none value on a dict in python won't work - Stack Overflow
def replace_none_values(): doc = db.events.find() for document in doc: for key, value in document.items(): if key == 'event': event_part = value for key1, value1 in event_part: if value1 is None: document['event'][key1] = 'No' db.events.save(document) replace_none_values() but the code in for key1, value1 in event_part: is not executed. I don't know why, what I'm doing wrong here? Can somebody help me please? ... I modified the question , because that mistake i did while writing the question, anyway the error that I have is somewhere else. ... Use the items method again since what you have is a nested dictionary.
๐ŸŒ
Iditect
iditect.com โ€บ faq โ€บ python โ€บ how-to-get-rid-of-none-values-in-dictionary-using-python.html
How to get rid of None values in dictionary using python?
original_dict = {'a': 1, 'b': None, 'c': 3, 'd': None} keys_to_remove = [key for key, value in original_dict.items() if value is None] for key in keys_to_remove: del original_dict[key] print(original_dict) "How to filter out None values from Python dictionary?"
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ dictionary โ€บ python-data-type-dictionary-exercise-41.php
Python: Drop empty Items from a given Dictionary - w3resource
# Iterate through the key-value pairs in 'dict1' and include them in the new dictionary if the value is not 'None'. dict1 = {key: value for (key, value) in dict1.items() if value is not None} # Print the new dictionary containing only non-empty items. print(dict1) ... Original Dictionary: {'c1': 'Red', 'c2': 'Green', 'c3': None} New Dictionary after dropping empty items: {'c1': 'Red', 'c2': 'Green'} ... Write a Python program to remove keys with values that are None, empty strings, or empty lists from a dictionary using dictionary comprehension.
๐ŸŒ
Tutorial Reference
tutorialreference.com โ€บ python โ€บ examples โ€บ faq โ€บ python-how-to-remove-none-from-dictionary
How to Handle None Values in Python Dictionaries: Removal and Replacement | Tutorial Reference
These methods create a new dictionary or modify the existing one to exclude keys associated with None values. This is the most concise and Pythonic way to create a new dictionary without None values: