[英]Iterate through dict key with a specific value
I have a dict like this: 我有这样的字典:
my_dict={val1:True, val2:False, val3:False, val4:True}
How do I iterate through this dict's keys that have value False
? 如何遍历此dict的值为False
的键?
Just use List comprehension
: 只需使用List comprehension
:
[key for key,val in my_dict.items() if val==False]
This will return a list
containing the keys
that have value
as False
. 这将返回一个包含value
False
的keys
的list
。 Now, it is a simple matter of going through the list
. 现在,通过list
是一件简单的事情。
#driver values : #driver值:
IN : my_dict = {'a': True,'b': False, 'c': True, 'd': False}
OUT : ['b','d']
You can do something like this: 你可以这样做:
>>> my_dict={'val1':True,'val2':False,'val3':False,'val4':True}
>>> [k for k, v in my_dict.items() if not v]
['val2', 'val3']
>>>
Simple solution of your problem : 简单解决您的问题:
for i,j in my_dict.items():
if j is False:
print(i)
Additional information : 附加信息 :
In python we can use
if something:
for checking truthy and falsy : 在python中我们可以使用if something:
用于检查truthy和falsy:
so : 所以:
for i,j in my_dict.items():
if not j:
print(i)
You can use generator expression : 您可以使用生成器表达式:
print(list((key for key,value in my_dict.items() if not value)))
You have to filter them first, this is a working example: 你必须先过滤它们,这是一个有效的例子:
for key in (k for k, v in my_dict.items() if not v):
print(key)
This works by going through all the (key, value) pairs, and iterating over the key
s that have a negative value
这是通过在所有的(键,值)对去,并遍历key
具有负小号value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.