read yaml file to dict in python

How to Read YAML File to Dict in Python

YAML stands for YAML Ain’t Markup Language, and is used to define different kinds of configurations and schemas for websites & databases. It is easy to use and understand. Sometimes you may want to convert YAML file to python dict, or write YAML to dict in Python. In this article, we will look at how to read YAML file to dict in Python.

The main benefits of using YAML files are that they portable across programming languages, extensive and support Unicode characters. It is more human-readable than other markup files like XML or even HTML for that matter. It supports a wide range of data types, including maps, lists and scalars.


How to Read YAML File to Dict in Python

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
     awsHostname: ip-someip
     serverName: somewebsite.com
     ipAddr: 192.168.0.1
     roles: [webserver,php]

We will use pyyaml library to parse YAML file. You can install with the following command.

$ sudo pip install pyyaml

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)

In the above code, we import pyyaml as yaml library. Then we open the data.yaml file using open() function and use yaml.safe_load() function .

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'}}

Here is another one.

>>> print(parsed_yaml['instance']['roles'])
['webserver', 'php']

You can even iterate through its items like you do in a dictionary.

>>> for key, value in parsed_yaml.iteritems():
    print key, value


environment us-east
roles ['webserver', 'php']
awsHostname ip-someip
serverName somewebsite.com
ipAddr 192.168.0.1
serverId someServer
Id i-aaaaaaaa

That’s it. In this article, we have looked at how to load YAML file to python dictionary, and also how to access its values.

Also read:

How to Delete Empty Lines from Text File in Linux
How to Install Supervisor in RHEL/Fedora/CentOS
How to Install OpenSSL in Ubuntu
How to Reset Root Password in Ubuntu
How to Sort CSV File in Python

Leave a Reply

Your email address will not be published.