Delete items in nested dictionary based on value.

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Wed Sep 13 19:31:05 EDT 2006


My first try, not much tested:

def clean(d):
    for key,val in d.items():
        if isinstance(val, dict):
            val = clean(val)
        if not 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}

Recursivity overflow problem: you can increase the recursivity limit,
of if you think you need it after some tests on your real data, then
you can use a stack (a python list, using append and pop methods) to
simulate recursivity. You probably don't have 300+ levels of nesting.

Bye,
bearophile




More information about the Python-list mailing list