1 / 7

How to Read YAML File to Dict in Python

Sometimes you may need to parse YAML file to dict or read YAML file to dict. Here is how to do it. #python #yaml<br><br>Visit https://techimbo.com/how-to-read-yaml-file-to-dict-in-python/

Download Presentation

How to Read YAML File to Dict in Python

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. How to Read YAML File to Dict in Python

  2. Step 1 Here are the steps to read YAML file to dict. Let us say you have the following YAML file at /home/ubuntu/data.yaml # An example YAML file instance: Id: i-aaaaaaaa environment: us-east serverId: someServer

  3. Step 1 continued awsHostname: ip-someip serverName: somewebsite.com ipAddr: 192.168.0.1 roles: [webserver,php]

  4. Install pyyaml We will use pyyaml library to parse YAML file. You can install with the following command. $ sudo pip install pyyaml

  5. Parse YAML Here is the code to parse this YAML file import yaml with open("/home/ubuntu/data.yaml", 'r') as stream: try: parsed_yaml=yaml.safe_load(stream) print(parsed_yaml) except yaml.YAMLError as exc: print(exc)

  6. View Result You can also use yaml.load() function to load YAML file. It is just that safe_load function will prevent python from executing any arbitrary code in the YAML file. Once the file is loaded you can display or process its values as per your requirement. The loaded YAML file works like a python object and you can reference its elements using keys. Here is an example. >>> print(parsed_yaml) {'instance': {'environment': 'us-east', 'roles': ['webserver', 'php'], 'awsHostname': 'ip-someip', 'serverName': 'somewebsite.com', 'ipAddr': '192.168.0.1', 'serverId': 'someServer', 'Id': 'i-aaaaaaaa'}}

  7. Thank You Visit for details https://techimbo.com/how-to-read-yaml-file-to-dict-in-pytho n/

More Related