Ajay Misra
Ajay Misra

Reputation: 210

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.

Upvotes: 2

Views: 235

Answers (1)

zwer
zwer

Reputation: 25829

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

Upvotes: 3

Related Questions