Want to access a value in a dictionary which is inside a list inside another dictionary

1k views Asked by At

I'm using Python3 with the boto3 package and I'm running describe_instances() to describe all of my instances. However the return type is a dictionary, now there are lists and other dictionaries inside the dictionary.

What I want to do for example is return only the "InstanceId" string or if I could return the entire "Instances" list that wouldn't be bad either.

ec2 = boto3.client(Make connection here)
response = ec2.describe_instances()
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(response)

The return type and the response code can be found here. http://boto3.readthedocs.org/en/latest/reference/services/ec2.html#EC2.Client.describe_instances

1

There are 1 answers

2
stan On BEST ANSWER

You can get the list of all InstanceIDs as a list with something like

import itertools
instance_list = list(itertools.chain.from_iterable([[i.get("InstanceId") for i in r.get("Instances", [])] for r in response['Reservations']]))