How I can get rid of None values in dictionary?

后端 未结 7 900
无人共我
无人共我 2020-12-03 02:26

Something like:

for (a,b) in kwargs.iteritems():
    if not b : del kwargs[a]

This code raise exception because changing of dictionary when

相关标签:
7条回答
  • 2020-12-03 03:22

    If you need to handle nested dicts, then you can leverage a simple recursive approach:

    # Python 2
    from collections import Mapping
    
    def filter_none(d):
        if isinstance(d, Mapping):
            return dict((k, filter_none(v)) for k, v, in d.iteritems() if v is not None)
        else:
            return d
    
    # Python 3
    from collections.abc import Mapping
    
    def filter_none(d):
        if isinstance(d, Mapping):
            return {k: filter_none(v) for k, v in d.items() if v is not None}
        else:
            return d
    
    0 讨论(0)
提交回复
热议问题