Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a dict value contains a word/string? [duplicate]

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"
like image 425
Nishant Singh Avatar asked Jul 05 '16 06:07

Nishant Singh


People also ask

Is there == for dict in python?

According to the python doc, you can indeed use the == operator on dictionaries.

Can you have duplicates in a dictionary?

However, there are a couple restrictions that dictionary keys must abide by. First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

How do you check if a value is already in a dictionary?

To check if a value exists in a dictionary, i.e., if a dictionary has/contains a value, use the in operator and the values() method. Use not in to check if a value does not exist in a dictionary.


3 Answers

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

like image 138
Harsh Trivedi Avatar answered Sep 20 '22 07:09

Harsh Trivedi


I also found this works

   elif inst ['Events'][0]['Code'] == "instance-stop":
                        if "[Completed]" in inst['Events'][0]['Description']:
                            print "Nothing to do here"
like image 28
Nishant Singh Avatar answered Sep 22 '22 07:09

Nishant Singh


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
like image 34
DeepSpace Avatar answered Sep 18 '22 07:09

DeepSpace