How I can get rid of None values in dictionary?

后端 未结 7 935
无人共我
无人共我 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:13

    To anybody who may interests, here's another way to get rid of None value. Instead of deleting the key, I change the value of None with a placeholder for the same key.

    One use case is applying with Spark RDD.map onto null valued JSON.

    def filter_null(data, placeholder="[spark]nonexists"):
        # Replace all `None` in the dict to the value of `placeholder`
        return dict((k, filter_null(v, placeholder) if isinstance(v, dict) else v if v 
    is not None else placeholder) for k, v in data.iteritems())
    

    Sample output:

    >>> filter_null({'a':None,'b':"nul", "c": {'a':None,'b':"nul"}})
    {'a': '[spark]nonexists', 'c': {'a': '[spark]nonexists', 'b': 'nul'}, 'b': 'nul'}
    

    For python3, change the iteritems() to items().

提交回复
热议问题