Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 246
JamesHudson81 Avatar asked Dec 12 '25 09:12

JamesHudson81


2 Answers

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}}
like image 101
Stephen Rauch Avatar answered Dec 15 '25 17:12

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

Result:

{'key1': {'subkey2': 7, 'subkey3': 5, 'subkey1': 2}}
like image 43
Rakesh Avatar answered Dec 15 '25 18:12

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!