Delete items in nested dictionary based on value.
Fuzzyman
fuzzyman at gmail.com
Wed Sep 13 19:59:57 EDT 2006
bearophileHUGS at lycos.com wrote:
> 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
Can you delete values from a dictionary whilst iterating over its items
?
Fuzzyman
http://www.voidspace.org.uk/python/index.shtml
>
> 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