在 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
Proper way to remove keys in dictionary with None values in Python
提问by Newboy11
What is the proper way to remove keys from a dictionary with value == None
in Python?
从None
Python 中具有值 == 的字典中删除键的正确方法是什么?
回答by mgilson
Generally, you'll create a new dict
constructed 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 dict
to avoid iterating the original dict
while 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)