简体   繁体   English

在python字典中检查元素是否存在且是否为真的正确方法是什么?

[英]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强制转换在那里,所以函数只返回TrueFalse

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 PYTHON:检查和编辑结构化数组中的元素(如果存在)的最快方法是什么? - PYTHON: What is the fastest way of checking and editing an element in a structured array if it exists? 根据值列表中的元素是否存在来过滤 python 字典的有效方法是什么? - What's the efficient way to filter a python dictionary based on whether an element in a value list exists? 检查元素是否存在 Python Selenium - Checking if an element exists with Python Selenium 从列表中为Python字典分配和显示值的正确方法是什么? - What is the proper way to assign and display values to a Python dictionary from a list? 在“ for”循环(Python)中从字典中删除项目的正确方法是什么? - What is the proper way of deleting item from a dictionary in “for” loop (Python)? 在 Python 中从嵌套字典中提取值的正确方法是什么? - What is the proper way to extract the value from nested dictionary in Python? 如果python的字典中至少存在某些键中的一种,哪种方法更好? - What is the better way if at least one of some keys exists in a dictionary in python? python:在字典中存在检查多个键的最佳方法是什么? - python: what is best way to check multiple keys exists in a dictionary? 检查列表中是否存在刮擦元素的Python - Python when checking if scraped element exists in list 检查Python Selenium是否存在HTML元素 - Checking if HTML element exists with Python Selenium
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM