How to check if a dict value contains a word/string?
本问题已经有最佳答案,请猛点这里访问。
我有一个简单的条件,需要检查dict值是否在特定键中包含say
例子:
1 2 3 4 5 6 7 8 | 'Events': [ { 'Code': 'instance-reboot'|'system-reboot'|'system-maintenance'|'instance-retirement'|'instance-stop', 'Description': 'string', 'NotBefore': datetime(2015, 1, 1), 'NotAfter': datetime(2015, 1, 1) }, ], |
我需要在启动时检查
'Descripton': '[Completed] The instance is running on degraded
hardware'
我该怎么做?我在找类似的东西
1 2 3 | if inst ['Events'][0]['Code'] =="instance-stop": if inst ['Events'][0]['Description'] consists '[Completed]": print"Nothing to do here" |
这应该有效。您应该使用
1 2 3 4 5 | "ab" in"abc" #=> True "abxyz" in"abcdf" #=> False |
所以在你的代码中:
1 2 3 4 | 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 2 3 | for key in inst['Events']: if 'instance-stop' in key['Code'] and '[Completed]' in key['Description']: # do something here |
我也发现了这个作品
1 2 3 | elif inst ['Events'][0]['Code'] =="instance-stop": if"[Completed]" in inst['Events'][0]['Description']: print"Nothing to do here" |
1 2 3 | for row in inst['Events']: if ("instance-stop" in row['Code'].split('|')) and ((row['Descripton'].split(' '))[0] == '[Completed]'): print"dO what you want !" |