20

I have a simple condition where i need to check if a dict value contains say [Complted] in a particular key.

example :

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

I need to check if the Description key contains [Complted] in it at starting. i.e

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

How can i do so ? I am looking for something like

if inst ['Events'][0]['Code'] == "instance-stop":
      if inst ['Events'][0]['Description'] consists   '[Completed]":
              print "Nothing to do here"
Nishant Singh
  • 3,055
  • 11
  • 36
  • 74
  • 1
    What is this line supposed to do? `'Code': 'instance-reboot'|'system-reboot'|'system-maintenance'|'instance-retirement'|'instance-stop'` – sidney Jul 05 '16 at 06:56
  • 1
    Why downvote for a potential duplicate? He has been careful enough to ask question with enough details.. – Harsh Trivedi Jul 05 '16 at 07:00
  • @HarshTrivedi Maybe because *"This question does not show any research effort..."*? – SiHa Jul 06 '16 at 07:31

4 Answers4

7

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 : )

Harsh Trivedi
  • 1,594
  • 14
  • 27
1

I also found this works

   elif inst ['Events'][0]['Code'] == "instance-stop":
                        if "[Completed]" in inst['Events'][0]['Description']:
                            print "Nothing to do here"
Nishant Singh
  • 3,055
  • 11
  • 36
  • 74
1

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
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0
for row in inst['Events']:
    if ( "instance-stop" in row['Code'].split('|')) and ((row['Descripton'].split(' '))[0] == '[Completed]'):
        print "dO what you want !"
Pratik Gujarathi
  • 929
  • 1
  • 11
  • 20