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"
3
  • 1
    What is this line supposed to do? 'Code': 'instance-reboot'|'system-reboot'|'system-maintenance'|'instance-retirement'|'instance-stop' Commented Jul 5, 2016 at 6:56
  • 1
    Why downvote for a potential duplicate? He has been careful enough to ask question with enough details.. Commented Jul 5, 2016 at 7:00
  • @HarshTrivedi Maybe because "This question does not show any research effort..."? Commented Jul 6, 2016 at 7:31

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

in is a keyword, not a method.
No need to check for != None and that is not the correct way to check for it. It should be is not None.
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"

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.