Proper way to remove keys in dictionary with None values in Python

后端 未结 6 1811
暗喜
暗喜 2020-12-05 04:11

What is the proper way to remove keys from a dictionary with value == None in Python?

相关标签:
6条回答
  • 2020-12-05 04:29

    You can also do this using the del command

       f = {};
       f['win']=None
       f
       => {'win': None}
       del f['win']
    

    Or if you want this in a function format you could do:

    def del_none_keys(dict):
        for elem in dict.keys():
            if dict[elem] == None:
               del dict[elem]
    
    0 讨论(0)
  • 2020-12-05 04:35

    Generally, you'll create a new dict constructed from filtering the old one. dictionary comprehensions are great for this sort of thing:

    {k: v for k, v in original.items() if v is not None}
    

    If you must update the original dict, you can do it like this ...

    filtered = {k: v for k, v in original.items() if v is not None}
    original.clear()
    original.update(filtered)
    

    This is probably the most "clean" way to remove them in-place that I can think of (it isn't safe to modify a dict while you're iterating over it)


    Use original.iteritems() on python2.x

    0 讨论(0)
  • 2020-12-05 04:38

    You could also take a copy of the dict to avoid iterating the original dict while altering it.

    for k, v in dict(d).items():
        if v is None:
            del d[k]
    

    But that might not be a great idea for larger dictionaries.

    0 讨论(0)
  • 2020-12-05 04:40

    For python 2.x:

    dict((k, v) for k, v in original.items() if v is not None)
    
    0 讨论(0)
  • 2020-12-05 04:41

    Maybe you'll find it useful:

    def clear_dict(d):
        if d is None:
            return None
        elif isinstance(d, list):
            return list(filter(lambda x: x is not None, map(clear_dict, d)))
        elif not isinstance(d, dict):
            return d
        else:
            r = dict(
                    filter(lambda x: x[1] is not None,
                        map(lambda x: (x[0], clear_dict(x[1])),
                            d.items())))
            if not bool(r):
                return None
            return r
    

    it would:

    clear_dict(
        {'a': 'b', 'c': {'d': [{'e': None}, {'f': 'g', 'h': None}]}}
    )
    
    ->
    
    {'a': 'b', 'c': {'d': [{'f': 'g'}]}}
    
    
    0 讨论(0)
  • 2020-12-05 04:44

    if you don't want to make a copy

    for k,v  in list(foo.items()):
       if v is None:
          del foo[k]
    
    0 讨论(0)
提交回复
热议问题