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"
According to the python doc, you can indeed use the == operator on dictionaries.
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.
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.
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 : )
I also found this works
elif inst ['Events'][0]['Code'] == "instance-stop":
if "[Completed]" in inst['Events'][0]['Description']:
print "Nothing to do here"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With