Python Yaml Sample Code

December 22, 2018

Install PyYAML.

pip install pyyaml

Parse yaml

import yaml

yaml_config = '''
user:
  name: Desmond
  number: 7
  fav_language:
    - Python
    - Kotlin
  friends: ['Mei Ru', 'Jackie', 'CJ']
'''

data = yaml.load(yaml_config)
name = data['user']['name']

Write/Output yaml.

print(yaml.dump(data, default_flow_style=False))
user:
  fav_language:
  - Python
  - Kotlin
  friends:
  - Mei Ru
  - Jackie
  - CJ
  name: Desmond
  number: 7
print(yaml.dump(data, default_flow_style=True))
{user: {fav_language: [Python, Kotlin], friends: [Mei Ru, Jackie, CJ], name: Desmond,
    number: 7}}
print(yaml.dump(data))
user:
  fav_language: [Python, Kotlin]
  friends: [Mei Ru, Jackie, CJ]
  name: Desmond
  number: 7

NOTE: Refer Python Yaml Read and Write File

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.