How to check if a dict value contains a word/string?

This question already has an answer here:

  • Does Python have a string 'contains' substring method? 13 answers

  • This should work. You should use in instead of consists . There is nothing called consists in python.

    "ab" in "abc"
    #=> True
    
    "abxyz" in "abcdf"
    #=> False
    

    So in your code:

    if inst['Events'][0]['Code'] == "instance-stop":
          if '[Completed]' in inst['Events'][0]['Description']
              # the string [Completed] is present
              print "Nothing to do here"
    

    Hope it helps : )


    我也发现这个作品

       elif inst ['Events'][0]['Code'] == "instance-stop":
                            if "[Completed]" in inst['Events'][0]['Description']:
                                print "Nothing to do here"
    

    Seeing that the 'Events' key has a list of dictionaries as value, you can iterate through all of them instead of hardcoding the index.

    Also, inst ['Events'][0]['Code'] == "instance-stop": will not be true in the example you provided.

    Try to do it this way:

    for key in inst['Events']:
        if 'instance-stop' in key['Code'] and '[Completed]' in key['Description']:
            # do something here
    
    链接地址: http://www.djcxy.com/p/9384.html

    上一篇: 如何使用python匹配字符串中的子串

    下一篇: 如何检查字典值是否包含单词/字符串?