简体   繁体   English

如何根据值从字典中筛选出密钥

[英]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.

相关问题 我不知道如何从嵌套字典中提取特定的键:值对 - I can't figure out how to extract specific key:value pairs from a nested dictionary 如何判断字典中特定键的值是否是字典,以便我可以基于此递归解决编程问题? - How do I tell if the value of a particular key in my dictionary is a dictionary so that I can solve programming questions based on this recursively? 如何在没有值的字典中打印键? - How do i print the key inside a dictionary, with out the value? 如何根据python中的字典值按日期范围过滤,否则按字典过滤列表? - How do I filter by a date range based on a dictionary value in python, otherwise filter a list by a dictionary? 如果键是一个元组,如何在字典中访问键的值? - How can I access the value of a key in a dictionary if the key is a tuple? 如何使用columns值作为字典的键,根据返回的值过滤pandas df的行 - How to filter rows of a pandas df using the columns value as the key to a dictionary based on its returned value 无法根据值检索字典中的键 - Can't retrieve key in a dictionary based on value 如何将列表中的值引用到字典键值? - How can I reference a value from a list to the dictionary key value? 从字典中筛选出密钥 - Filter out key from dictionary 根据该字典中某个键的特定值过滤字典列表 - filter list of dictionaries based on a particular value of a key in that dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM