70 likes | 79 Views
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/
E N D
How to Read YAML File to Dict in Python
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
Step 1 continued awsHostname: ip-someip serverName: somewebsite.com ipAddr: 192.168.0.1 roles: [webserver,php]
Install pyyaml We will use pyyaml library to parse YAML file. You can install with the following command. $ sudo pip install pyyaml
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)
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'}}
Thank You Visit for details https://techimbo.com/how-to-read-yaml-file-to-dict-in-pytho n/