[英]What is the proper way of checking if element exists and is true in a python dictionary?
someDict = {'foo': True}
if 'foo' in someDict and someDict['foo']:
print 'success'
Following code works fine. 以下代码工作正常。 I'm just wondering if there is a better/shorter way of checking if key exists and its value is true.
我只是想知道是否有更好/更短的方法来检查密钥是否存在且其值是否为真。
someDict.get('foo')
This will return None if foo
is not in someDict
, otherwise it will return the value found. 如果
foo
不在someDict
,则返回None,否则返回找到的值。 You can optionally pass a second argument which will be the value returned if it does not exist. 您可以选择传递第二个参数,如果该参数不存在,则返回该值。
Nope. 不。 If you're doing this a lot, you may want to write a function to do it, though.
如果你正在做很多事情,你可能想要编写一个函数来做到这一点。
def ExistsTrue(d, name):
return name in d and bool(d[name])
# usage
ExistsTrue(someDict, 'foo')
I put the bool
cast in there so the function only returns True
or False
. 我把
bool
强制转换在那里,所以函数只返回True
或False
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.