【问题标题】:How parsing of dictionary in python works?python中字典的解析是如何工作的?
【发布时间】:2022-01-15 23:44:07
【问题描述】:

我有以下 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 代码

【问题讨论】:

  • 感谢@iain-shelvington 的指点。我已经更新了它。输出的差异只是因为 for 循环中的逗号(,)

标签: python dictionary yaml


【解决方案1】:

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

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多