python - How to access the dict value? -
i have response syntax of type dict
:
{ 'stoppinginstances': [ { 'instanceid': 'string', 'currentstate': { 'code': 123, 'name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' }, 'previousstate': { 'code': 123, 'name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' } }, ] }
now if need check if currentstate stopping
how so?
print "stopping instance now",response['stoppinginstances'] instance in response['stoppinginstances']: if instance['currentstate']['name'] == "stopping": print "still stooping" if instance['currentstate']['name'] == "stopped": print "instance stopped" print "now starting instance" response_new = client.start_instances(instanceids=[instance_id]) start_instance in response_new['startinginstances']: if start_instance['currentstate']['name'] == "running": print "instance , running" else: print "some error occured!!"
your data contains list enclosing outer dict values, , not simple nested dictionaries suppose. need index list, access nested dict values via keys:
response['stoppinginstances'][0]['currentstate']['name'] # ^
and in if
block:
if response['stoppinginstances'][0]['currentstate']['name'] == "stopped": print "instance stopped"
Comments
Post a Comment