[Python-ideas] Syntax to conditionally define a field in a dict

Jonathan Fine jfine2358 at gmail.com
Fri Apr 26 11:47:40 EDT 2019


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190426/8ed5458e/attachment.html>


More information about the Python-ideas mailing list