26 Apr
2019
26 Apr
'19
3:47 p.m.
Hi Joshua Sounds to me that you want a solution soon, rather than in a future version of Python. Perhaps this works for you. def prune_nones(d): for k, v in list(d.items()): if v is None: del d[k] if type(v) is dict: prune_nones(v)
d = dict(a=1, b=2, c=None) prune_nones(d) {'a': 1, 'b': 2}
d = dict(a=1, b=2, c=None, d=dict(e=None, f=3)) prune_nones(d) {'a': 1, 'b': 2, 'd': {'f': 3}}
I hope this helps. By the way, the list(d.items()) in the loop is to avoid RuntimeError: dictionary changed size during iteration -- Jonathan