解析嵌套的Python dict

时间:2018-03-26 19:46:14

标签: python json dictionary nested

我有一个嵌套字典,我试图解析,似乎不知道如何访问第三级项目。感谢帮助 这是我的字典

{
    "FunctionName": "RDSInstanctStart",
    "LastModified": "2018-03-24T07:19:56.792+0000",
    "MemorySize": 128,
    "Environment": {
        "Variables": {
            "DBInstanceName": "test1234"
        }
    },
    "Version": "$LATEST",
    "Role": "arn:aws:iam::xxxxxxx:role/lambda-start-RDS",
    "Timeout": 3,
    "Runtime": "python2.7",
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "CodeSha256": "tBdB+UDA9qlONGb8dgruKc6Gc82gvYLQwdq432Z0118=",
    "Description": "",
    "VpcConfig": {
        "SubnetIds": [],
        "SecurityGroupIds": []
    },
    "CodeSize": 417,
    "FunctionArn": "arn:aws:lambda:us-east-1:xxxxxxxx:function:RDSInstanctStart",
    "Handler": "lambda_function.lambda_handler"
}

我正在尝试访问键“Variables”的值 到目前为止,这是我的代码:

try:           

 for evnt in funcResponse['Environment']['Variables']['DBInstanceName']:
            print (evnt[0])
except ClientError as e:
        print(e)

我得到的结果是

t
e
s
t
1
2
3
4    

如果我没有给出envt变量的索引,我会收到类型错误。

1 个答案:

答案 0 :(得分:4)

funcResponse['Environment']['Variables']['DBInstanceName']是一个单字符串,但您正在循环它。字符串是单个字符的序列。

如果你这样做,你就会得到同样的结果:for character in "test1234": print(character[0])(你也可以删除[0]索引,因为character就像字符串一样,其中包含一个字符)。

不要循环,只需打印:

evnt = funcResponse['Environment']['Variables']['DBInstanceName']
print(evnt)

如果您想打印所有环境变量,那么您必须循环遍历funcResponse['Environment']['Variables']字典的项目:

for name, value in funcResponse['Environment']['Variables'].items():
    print(name, value, sep=': ')

无论如何,funcResponse['Environment']['Variables']只是一本字典。将['DBInstanceName']添加到末尾会为您提供'DBInstanceName'密钥的值。