简体   繁体   中英

Accessing Nested Dictionary - Python

I have below Dictionary those values I am pulling from aws S3 bucket -

{u'Policy': u'{"Version":"2012-10-17","Statement":[{"Sid":"AddPerm","Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::elliemaetestbucket1/*"},{"Sid":"AddPerm1","Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::elliemaetestbucket1/*"}]}'}

I want to read " Sid " value and compare it with a string that I am getting from my yaml file. Dictionary can have multiple sids but I need to stop where my sid matches with the string that I am pulling from yaml. I am sure I am missing something very simple. But I have tried almost all the solutions most of the time I get unicode object not callable error. Can somebody please provide some direction on how I can access it. I know this would be something very simple but I am sorry I am stuck at this from 2 days.

Your data's Policy key holds a literal JSON, you have to parse it first before you can access its nested fields:

import json

policy = json.loads(your_data["Policy"])

print(policy["Statement"][0]["Sid"])  # Sid of the first Statement
print(policy["Statement"][1]["Sid"])  # Sid of the second Statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM