Access YAML Content Using Dot Notation in Python

This tutorial explores various methods to access YAML file content using dot notation in Python.

You’ll learn how to transform YAML data into objects that allow attribute-style access.

 

 

Using types.SimpleNamespace

You can use types.SimpleNamespace to convert YAML data into an object with accessible attributes.

import yaml
from types import SimpleNamespace
yaml_data = """
person:
  name: Amira
  age: 30
  address:
    city: Cairo
    street: Nile Street
"""
data = yaml.safe_load(yaml_data)
person = SimpleNamespace(**data['person'])
print(person.name)
print(person.address['city'])

Output:

Amira
Cairo

Accessing person.name retrieves the name, and person.address['city'] accesses the city within the nested address dictionary.

 

Using python-box Library

You can use the python-box library to provide dot notation access to YAML data.

from box import Box
import yaml
yaml_data = """
company:
  name: NileTech
  employees:
    - name: Karim
      role: Developer
    - name: Layla
      role: Designer
"""
data = yaml.safe_load(yaml_data)
box_data = Box(data)
print(box_data.company.name)
print(box_data.company.employees[1].role)

Output:

NileTech
Designer

Here, box_data.company.name accesses the company name, and box_data.company.employees[1].role retrieves the role of the second employee.

 

Using addict Library

You can use the addict library to navigate YAML data using dot notation.

from addict import Dict
import yaml
yaml_data = """
settings:
  version: 1.0
  paths:
    home: /home/amira
    config: /home/amira/config.yaml
  features:
    authentication: true
    logging: false
"""
data = yaml.safe_load(yaml_data)
addict_data = Dict(data)
print(addict_data.settings.version)
print(addict_data.settings.paths.config)

Output:

1.0
/home/amira/config.yaml

Here, addict_data.settings.version accesses the version, and addict_data.settings.paths.config retrieves the configuration path.

 

Using DotMap Library

You can use the DotMap library to transform YAML data into a dot-accessible object.

from dotmap import DotMap
import yaml
yaml_data = """
database:
  host: localhost
  port: 5432
  credentials:
    user: Ahmed
    password: secret
"""
data = yaml.safe_load(yaml_data)
dot_data = DotMap(data)
print(dot_data.database.host)
print(dot_data.database.credentials.user)

Output:

localhost
Ahmed

Access dot_data.database.host to get the database host, and dot_data.database.credentials.user to obtain the username.

Leave a Reply

Your email address will not be published. Required fields are marked *