Delete items in nested dictionary based on value.

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Wed Sep 13 19:34:55 EDT 2006


Better:

def clean(d):
    for key,val in d.items():
        if isinstance(val, dict):
            val = clean(val)
        if val is None or val == {}:
            del d[key]
    return d

a = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None}
print clean(a) # Out: {1: {2: 2, 3: {2: 2}}, 2: 2}
b = {1: {1: {1: None, 2: {1: None}}}, 2: 2, 3: None}
print clean(b) # Out: {2: 2}
c = {1: {1: {1: None, 2: {1: None}}}, 2: 2, 3: 0}
print clean(c) # Out: {2: 2, 3: 0}




More information about the Python-list mailing list