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

后端 未结 6 1826
暗喜
暗喜 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: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.

提交回复
热议问题