【问题标题】:Parse nested Python dict解析嵌套的 Python 字典
【发布时间】:2018-09-05 01:39:32
【问题描述】:

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

{
    "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"
}

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

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

【问题讨论】:

  • 另一方面,您可能对 dpath 或其竞争对手之一感兴趣,将嵌套集合视为具有复杂路径的平面集合,例如用于键的 'Environment/Variables/DBInstanceName'。

标签: python json dictionary nested


【解决方案1】:

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

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

不要循环,只打印:

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

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

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

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

【讨论】:

  • 谢谢马丁。我现在知道了。还要感谢 sn-p 循环所有环境变量。在某个时候,我也会这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 2013-07-28
  • 2011-06-06
相关资源
最近更新 更多