gpt4 book ai didi

python - 解析嵌套的 Python 字典

转载 作者:行者123 更新时间:2023-11-28 22:19:44 26 4
gpt4 key购买 nike

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

{
"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 变量的索引,我会得到一个类型错误。

最佳答案

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' 键的值。

关于python - 解析嵌套的 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49499444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com