简体   繁体   English

访问嵌套字典-Python

[英]Accessing Nested Dictionary - Python

I have below Dictionary those values I am pulling from aws S3 bucket - 我在字典下面有我从AWS S3存储桶中提取的那些值-

{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. 我想读取“ Sid ”值,并将其与从yaml文件中获取的字符串进行比较。 Dictionary can have multiple sids but I need to stop where my sid matches with the string that I am pulling from yaml. 字典可以有多个sid,但是我需要在sid与从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. 但是我大多数时候都尝试了几乎所有的解决方案,但都遇到了unicode对象无法调用的错误。 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. 我知道这将是非常简单的事情,但是对不起,我从2天开始就一直停留在此。

Your data's Policy key holds a literal JSON, you have to parse it first before you can access its nested fields: 数据的Policy密钥包含文字JSON,您必须先解析它,然后才能访问其嵌套字段:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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