Getting rid of keys in nested dictionary that contain None values


I have the following dict:

dict_2 = {
    'key1': {'subkey1': 2, 'subkey2': 7, 'subkey3': 5},
    'key2': {'subkey1': None, 'subkey2': None, 'subkey3': None},

I am looking forward to clean dict_2 from those None values in the subkeys, by removing the entire key with its nested dict:

In short my output should be:


What I tried was :


for k,v in dict_2.items():
    dictionary={k: dict_2[k] for k in dict_2 if not None (dict_2[k]
    if bool(glob_dict)==False:


My current output is :

TypeError: 'NoneType' object is not callable

I am not really sure if the loop is the best way to get rid of the None values of the nested loop, and I am not sure either on how to express that I want to get rid of the None values.

Asked By: JamesHudson81



A recursive solution to remove all None, and subsequent empty dicts, can look this:


def remove_empties_from_dict(a_dict):
    new_dict = {}
    for k, v in a_dict.items():
        if isinstance(v, dict):
            v = remove_empties_from_dict(v)
        if v is not None:
            new_dict[k] = v
    return new_dict or None

Test Code:

dict_2 = {
    'key1': {'subkey1': 2, 'subkey2': 7, 'subkey3': 5},
    'key2': {'subkey1': None, 'subkey2': None, 'subkey3': None},


{'key1': {'subkey1': 2, 'subkey2': 7, 'subkey3': 5}}
Answered By: Stephen Rauch
dict_2={'key1':{'subkey1':2,'subkey2':7,'subkey3':5} ,'key2':{'subkey1':None,'subkey2':None,'subkey3':None}}

d = {}
for k, v in dict_2.iteritems():
    if any(v.values()):
        d[k] = v
print d


{'key1': {'subkey2': 7, 'subkey3': 5, 'subkey1': 2}}
Answered By: Rakesh

You can use a NestedDict.

from ndicts.ndicts import NestedDict

dict_2 = {
    'key1': {'subkey1': 2, 'subkey2': 7, 'subkey3': 5},
    'key2': {'subkey1': None, 'subkey2': None, 'subkey3': None},
nd = NestedDict(dict_2)
nd_filtered = NestedDict()

for key, value in nd.items():
    if value is not None:
        nd_filtered[key] = value

To get the result as a dictionary

>>> nd_filtered.to_dict()
{'key1': {'subkey1': 2, 'subkey2': 7, 'subkey3': 5}}

To install ndicts pip install ndicts

Answered By: edd313

Easiest and simplest way to solve this problem

my_d = {‘a’:1,’b’:None,’c’:2,’d’:{‘e’:None,’f’:3}}


my_n_d = {}
my_n1_d = {}
for i , j in my_d.items():
    if j is not None:
        my_n_d[i] = j
    if isinstance(j,dict):
        for key in j:
            if j[key] is not None:
                my_n1_d[key] = j[key]
                my_n_d[i] = my_n1_d

{‘a’: 1, ‘c’: 2, ‘d’: {‘f’: 3}}

Answered By: Deepali Srivastava
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.