Home > Blockchain >  How parsing of dictionary in python works?
How parsing of dictionary in python works?

Time:12-12

I have below template.yaml file:

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

When I am trying to parse it using below python code:

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()

I am getting key as output:

ApiGatewayDeployment

But when I am parsing it using below code:

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()

I am getting dictionary as output:

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

Can anyone please explain this logic?

Edit: updated 2nd python code

CodePudding user response:

This doesn't have anything to do with how the dictionary is parsed, but rather the way that you're trying to iterate over its contents. The difference is a single comma:

for res in cfn["Resources"]:

vs:

for res in cfn["Resources"],:

Adding a trailing comma to an expression turns it into a tuple (i.e. it adds another level of container to it).

In the first version, res is iterating over the keys of cfn["Resources"]. (Note: you might want to iterate over cfn["Resources"].values() instead!)

In the second version, res is iterating over a tuple that contains cfn["Resources"] itself.

Hence:

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

is exactly equivalent to just doing:

    print(cfn["Resources"])

Here's a simpler example using a regular old list:

>>> 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]
  • Related