如何检查字典值是否包含某个单词/字符串?

20

我有一个简单的条件,需要检查字典中某个键的值是否包含特定的字符串[Completed]

示例

'Events': [
                {
                    'Code': 'instance-reboot'|'system-reboot'|'system-maintenance'|'instance-retirement'|'instance-stop',
                    'Description': 'string',
                    'NotBefore': datetime(2015, 1, 1),
                    'NotAfter': datetime(2015, 1, 1)
                },
            ],

我需要检查Description键是否以[Completed]开头。即:

'Descripton': '[Completed] The instance is running on degraded hardware'

我该如何做?我正在寻找类似以下方式的解决方案:

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

1
这行代码的作用是什么? 'Code': 'instance-reboot'|'system-reboot'|'system-maintenance'|'instance-retirement'|'instance-stop' - sidney
1
为什么要对潜在的重复问题进行负评?他已经足够小心地提出了带有足够细节的问题。 - Harsh Trivedi
也许是因为“这个问题没有展示任何研究努力……”? - SiHa
4个回答

7
这应该可以运行。你应该使用in代替consists。在Python中没有叫做consists的东西。
"ab" in "abc"
#=> True

"abxyz" in "abcdf"
#=> False

因此,在您的代码中:

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

希望能帮到你:)

in 是一个关键字,而不是一个方法。 - sidney
1
不需要检查 != None,这也不是正确的检查方式。应该使用 is not None - RedX

1

我也发现这个有效。

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

1

由于 'Events' 键的值是一个字典列表,你可以遍历所有字典而不是硬编码索引。

此外,在你提供的示例中,inst ['Events'][0]['Code'] == "instance-stop": 不会为真。

尝试这样做:

for key in inst['Events']:
    if 'instance-stop' in key['Code'] and '[Completed]' in key['Description']:
        # do something here

0
for row in inst['Events']:
    if ( "instance-stop" in row['Code'].split('|')) and ((row['Descripton'].split(' '))[0] == '[Completed]'):
        print "dO what you want !"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接