Reputation: 447
I'm trying to get a for loop to work in boto3 and even though I have it working, it was hard to figure it out. At the moment I have:
`spot_requests = ec2.describe_spot_instance_requests()
for index in spot_requests['SpotInstanceRequests']:
instanceID = index["InstanceId"]
instanceState = index["State"]
spotRequestID = index["SpotInstanceRequestId"]
print(f'{instanceID} is {instanceState} and has a request ID of {spotRequestID}')`
which returns something like:
"I-1234556 IS disabled and has a request ID of sir-12344"
what I don't understand is why the index needs to be there after the = sign and why it errors if I just have:
instanceID = ["InstanceId"]
Also, I understand how dictionaries work, you reference the dictionary name and then in [square brackets] the key that you want to find the value for. However, when I try this (which is correct apparently)
`describe_instance = ec2.describe_instances()
for item2 in describe_instance['Reservations']:
instance_state = item2['Instances'][0]["State"]["Name"]`
I don't understand what the [0] is doing as there is no key in the dictionary with 0 value. And what would I do if there was a nested dictionary in this? would it be something like this:
describe_instance = ec2.describe_instances()
for item2 in describe_instance['Reservations']:
instance_state = item2['Instances'][0]["State"]["Name"][0]["Nested value I want to find"]
thank you
Upvotes: 0
Views: 148
Reputation: 140
what I don't understand is why the index needs to be there after the = sign and why it errors if I just have:
"index" is there because that is the dict that you want to get the specified value from.
I don't understand what the [0] is doing as there is no key in the dictionary with 0 value.
The [<number>] syntax indicates that you are trying to get a value from a a list, where the number indicates which index in the list you want to get. In you specific case the 'Instances' object in item2 is a list of dicts containing information about all the EC2 instances. Which is why you can use ['State']['Name'] to get the name of the state that the instance is currently in.
And what would I do if there was a nested dictionary in this? would it be something like this:
If the 'Name' field would contain a list of dicts (which wouldn't make sense) then you could do what you are suggesting in your last example.
Upvotes: 1