【问题标题】:How to check if a dict value contains a word/string? [duplicate]如何检查字典值是否包含单词/字符串? [复制]
【发布时间】:2016-11-06 21:45:15
【问题描述】:

我有一个简单的条件,我需要检查 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': '[Completed] 实例在降级上运行 硬件'

我该怎么做?我正在寻找类似的东西

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

【问题讨论】:

  • 这条线应该做什么? 'Code': 'instance-reboot'|'system-reboot'|'system-maintenance'|'instance-retirement'|'instance-stop'
  • 为什么不赞成潜在的重复?他已经足够小心地提出足够详细的问题..
  • @HarshTrivedi 也许是因为“这个问题没有显示任何研究工作......”

标签: python dictionary


【解决方案1】:

这应该可行。您应该使用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 是关键字,而不是方法。
  • 无需检查!= None,这不是检查它的正确方法。应该是is not None
【解决方案2】:

看到'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】:
    for row in inst['Events']:
        if ( "instance-stop" in row['Code'].split('|')) and ((row['Descripton'].split(' '))[0] == '[Completed]'):
            print "dO what you want !"
    

    【讨论】:

      【解决方案4】:

      我也发现这行得通

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

      【讨论】:

        猜你喜欢
        • 2020-03-16
        • 1970-01-01
        • 1970-01-01
        • 2014-01-25
        • 2017-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多