在 Python 中使用 None 值删除字典中键的正确方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33797126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:00:19  来源:igfitidea点击:

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

pythondictionary

提问by Newboy11

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

NonePython 中具有值 == 的字典中删除键的正确方法是什么?

回答by mgilson

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

通常,您将dict通过过滤旧构造来创建一个新构造。字典理解非常适合这类事情:

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

If you mustupdate 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)

这可能是我能想到的就地删除它们的最“干净”的方式(在迭代时修改 dict 是不安全的)



Use original.iteritems()on python2.x

original.iteritems()在 python2.x 上使用

回答by Josh Weinstein

You can also do this using the del command

您也可以使用 del 命令执行此操作

   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]

回答by Paul Rooney

You could also take a copy of the dictto avoid iterating the original dictwhile altering it.

您还可以复制 ,dict以避免dict在更改原始文件时对其进行迭代。

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.

但这对于较大的词典来说可能不是一个好主意。

回答by user2340939

For python 2.x:

对于python 2.x

dict((k, v) for k, v in original.items() if v is not None)