简体   繁体   中英

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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM