How I can get rid of None values in dictionary?

后端 未结 7 919
无人共我
无人共我 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 02:57

    The recursive approach to also filter nested lists of dicts in the dictionary:

    def filter_none(d):
    if isinstance(d, dict):
        return {k: filter_none(v) for k, v in d.items() if v is not None}
    elif isinstance(d, list):
        return [filter_none(v) for v in d]
    else:
        return d
    

    Sample output:

    data = {'a': 'b', 'c': None, 'd':{'e': 'f', 'h': None, 'i':[{'j': 'k', 'l': None}]}}
    print(filter_none(data))
    >>> {'a': 'b', 'd': {'e': 'f', 'i': [{'j': 'k'}]}}
    

提交回复
热议问题