python 中的字典解析是如何工作的?

How parsing of dictionary in python works?

我有以下 template.yaml 个文件:

Resources:
  ApiGatewayDeployment:
    Type: AWS::ApiGateway::Deployment
    Properties:
      RestApiId: ApiGateway

当我尝试使用下面的 python 代码解析它时:

import pathlib
import yaml


def main():
    template_file = pathlib.Path('template.yaml')
    cfn = yaml.safe_load(template_file.read_text())
    for res in cfn["Resources"]:
        print(res)


if __name__ == "__main__":
    main()

我正在获取密钥作为输出:

ApiGatewayDeployment

但是当我使用下面的代码解析它时:

import pathlib
import yaml


def main():
    template_file = pathlib.Path('template.yaml')
    cfn = yaml.safe_load(template_file.read_text())
    for res in cfn["Resources"],:
        print(res)


if __name__ == "__main__":
    main()

我正在获取字典作为输出:

{'ApiGatewayDeployment': {'Type': 'AWS::ApiGateway::Deployment', 'Properties': {'RestApiId': 'ApiGateway'}}}

谁能解释一下这个逻辑?

编辑:更新了第二个 python 代码

这与字典的解析方式没有任何关系,而是与您尝试迭代其内容的方式有关。区别是一个逗号:

for res in cfn["Resources"]:

对比:

for res in cfn["Resources"],:

向表达式添加尾随逗号会将其转换为元组(即向其添加另一层容器)。

在第一个版本中,res 迭代 cfn["Resources"] 的键。 (注意:您可能想要遍历 cfn["Resources"].values()!)

在第二个版本中,res 迭代包含 cfn["Resources"] 本身的元组。

因此:

    for res in cfn["Resources"],:
        print(res)

完全等同于:

    print(cfn["Resources"])

这是一个使用常规旧列表的简单示例:

>>> arr = [1, 2, 3]
>>> for i in arr:
...     print(i)
...
1
2
3
>>> for i in arr,:  # note the comma!
...     print(i)
...
[1, 2, 3]