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

时间:2016-07-05 06:50:19

标签: python dictionary

我有一个简单的条件,我需要检查dict值是否包含特定键中的[Complted]

示例

'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键中是否包含[Complted]。即

  

'Descripton':'[已完成]实例正在降级运行   硬件'

我该怎么办?我正在寻找像

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

4 个答案:

答案 0 :(得分:3)

这应该有效。您应该使用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"

希望有所帮助:)

答案 1 :(得分:1)

我也发现了这个作品

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

答案 2 :(得分: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

答案 3 :(得分:0)

Add-RangeMapping
相关问题