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

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

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

6条回答
  •  旧时难觅i
    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

提交回复
热议问题