Search code examples
pythondictionarynested

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:

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

What I tried was :

glob_dict={}

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

print(glob_dict)

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.


Solution

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

    Code:

    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},
    }
    print(remove_empties_from_dict(dict_2))
    

    Results:

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