Home > Enterprise >  Return value of key from dictionary nested in a list Python
Return value of key from dictionary nested in a list Python

Time:02-15

I have the following variable in my python script:

response = {"tasks": [{"attachments": [{"id": "id123xyz", "type": "ElasticNetworkInterface", "status": "PRECREATED", "details": [{"name": "john doe"}] }]}]}

I am simply trying to return the value of status. However, I'm unable to do so.

CodePudding user response:

You need to index into each dictionary and list that the status is inside.

You can do the following:

# Prints "PRECREATED"
print(response["tasks"][0]["attachments"][0]["status"])

CodePudding user response:

you need to access the dictionary and the list that is inside:

status = response['tasks'][0]['attachments'][0]['status']

#output
'PRECREATED'

CodePudding user response:

In order to retrieve the status, you can do this

response['tasks'][0]['attachments'][0]['status']

If you would like to extract to dictionary or array of id and status then we can do:

dict([(attachment['id'], attachment['status']) for task in response['tasks'] for attachment in task['attachments']])

returns:
{'id123xyz': 'PRECREATED'}
  • Related