[英]How can I filter a key out of a dictionary based on the value
I have this dict : 我有这个命令:
mydict = {'Andreas': 0.4833775399766172, 'Anh': nan, 'Maryse': 0.61436719272499474, 'Darren': -0.44898819782452443, 'Jesse': 0.14565852997686479, 'Mitchell': nan}
The nan's give me no information at all so I want to filter them out. nan根本不提供任何信息,因此我想将其过滤掉。
for k, v in mydict.iteritems():
if v == 'nan':
del mydict[v]
I tried this, but it doesn't work. 我试过了,但是没有用。 Could anyone help me?
有人可以帮我吗? Thanks in advance.
提前致谢。
You need to use the key not the value and you cannot delete from a dict you are iterating over, you need to copy: 您需要使用键而不是值,并且不能从要迭代的字典中删除,需要复制:
for k, v in mydict.copy().items():
if v == "nan":
del mydict[k]
print(mydict)
Whatever nan
actually is whether a string or something else you need to use the key, mydict[v]
will give you a keyError and changing the size of the dict will give you a RuntimeError: dictionary changed size during iteration
无论
nan
其实是一个字符串是否或者你需要使用密钥别的东西, mydict[v]
会给你一个KeyError异常和改变字典的大小会给你一个RuntimeError: dictionary changed size during iteration
You need to use math.isnan to check the value. 您需要使用math.isnan来检查该值。
import math
result = {k:v for (k,v) in d.iteritems() if not math.isnan(v)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.