how do check if a value exists in python

This question already has an answer here:

  • Check if a given key already exists in a dictionary 18 answers

  • 您可以使用in这样的:

    if "virtualDisk.totalReadLatency" in counterValues:
        doSomething()
    else:
        pass
    

    You can use a try/except block (according to the Zen of Python, it's better to ask for forgiveness than permission ;-)

    try:
         # your lookup
    except KeyError:
         # your error handling
    

    This way you can wrap all key-lookups into one try (better, refactor it to a single function).


    字典有.get()方法,如果你想替换一个默认值,如果这个键不存在:

    ReadLatency = counterValues.get('virtualDisk.totalReadLatency', 0)  # 0 is default
    
    链接地址: http://www.djcxy.com/p/28882.html

    上一篇: 检查密钥是否在字典中?

    下一篇: 如何检查python中是否存在一个值