Python YAML
last modified November 19, 2026 Python 3.15
In this article we show how to work with the YAML format in Python using the PyYAML library.
YAML format
YAML (YAML Ain't Markup Language) is a human-readable data
serialization language. It is mostly used for configuration files, for
example in Docker Compose, Kubernetes, Ansible, and GitHub Actions. The
recommended file extension is .yaml.
YAML has three kinds of data: scalars (strings, numbers, booleans, null), sequences (lists), and mappings (dictionaries). Structure is expressed by indentation with spaces; tabs are not allowed.
Python has no YAML module in the standard library. The two common libraries are PyYAML, which implements YAML 1.1, and ruamel.yaml, which implements YAML 1.2 and can keep comments when it rewrites a file. In this article we use PyYAML.
$ pip install pyyaml
Loading a string
The yaml.safe_load function parses a YAML document and returns
the corresponding Python object.
#!/usr/bin/python
import yaml
document = '''
name: falcon
speed: 389
weight: 1.2
wild: true
owner: null
'''
data = yaml.safe_load(document)
print(data)
for key, value in data.items():
print(f'{key:7} {value!r:10} {type(value).__name__}')
The document is a mapping, so we get a dictionary. PyYAML converts the
scalars to Python types: 389 becomes an integer,
1.2 a float, true a boolean, and
null becomes None. Unquoted text is a string.
$ python load_string.py
{'name': 'falcon', 'speed': 389, 'weight': 1.2, 'wild': True, 'owner': None}
name 'falcon' str
speed 389 int
weight 1.2 float
wild True bool
owner None NoneType
Reading a file
We can pass an open file to safe_load. We use the following
file:
raincoat: 1 coins: 5 books: 23 spectacles: 2 chairs: 12 pens: 6
The file contains a mapping of item names to counts.
#!/usr/bin/python
import yaml
with open('items.yaml') as f:
items = yaml.safe_load(f)
print(items)
print(sum(items.values()), 'items in total')
most = max(items, key=items.get)
print('most:', most, items[most])
The result is an ordinary dictionary, so we can sum its values and look for
the largest one with max. The keys keep the order of the file.
$ python read_yaml.py
{'raincoat': 1, 'coins': 5, 'books': 23, 'spectacles': 2, 'chairs': 12, 'pens': 6}
49 items in total
most: books 23
Nested data
Mappings and sequences can be nested. A configuration file is a typical example.
server:
host: localhost
port: 8080
workers: 4
database:
url: postgresql://localhost/shop
pool: {min: 2, max: 10}
admins:
- name: Lucy Black
email: lucy@example.com
- name: Paul Novak
email: paul@example.com
features: [search, export, dark-mode]
The file uses both styles of YAML collections: block style, with one item per line, and flow style, with brackets and braces as in JSON.
#!/usr/bin/python
import yaml
with open('config.yaml') as f:
config = yaml.safe_load(f)
print(config['server']['port'])
print(config['database']['pool'])
print(config['features'])
for admin in config['admins']:
print(admin['name'], '<' + admin['email'] + '>')
timeout = config['server'].get('timeout', 30)
print('timeout:', timeout)
Both styles load into the same dictionaries and lists. A list of mappings,
such as admins, becomes a list of dictionaries. For optional
settings we use the get method with a default value.
$ python nested.py
8080
{'min': 2, 'max': 10}
['search', 'export', 'dark-mode']
Lucy Black <lucy@example.com>
Paul Novak <paul@example.com>
timeout: 30
Implicit typing
YAML guesses the type of unquoted scalars. Under YAML 1.1 rules, which PyYAML follows, some guesses are surprising.
#!/usr/bin/python
import yaml
document = '''
country: NO
answer: yes
switch: on
version: 3.10
mode: 0755
duration: 3:20
big: 1_000_000
date: 2026-11-19
quoted: "NO"
'''
for key, value in yaml.safe_load(document).items():
print(f'{key:8} {value!r:25} {type(value).__name__}')
The country code NO (Norway) becomes False, as do
no and off; yes and on
become True. The version 3.10 is a float equal to
3.1, 0755 is an octal number, 3:20 is a
base-60 number (200), and a date becomes a datetime.date. Quoting
a value keeps it a string, so values such as versions, codes, and ZIP codes
should be quoted.
$ python implicit_types.py country False bool answer True bool switch True bool version 3.1 float mode 493 int duration 200 int big 1000000 int date datetime.date(2026, 11, 19) date quoted 'NO' str
Multiple documents
A YAML stream can contain several documents separated with
---.
cities: - Bratislava - Kosice - Trnava --- companies: - Eset - Slovnaft - Matador
The file contains two documents.
#!/usr/bin/python
import yaml
with open('data.yaml') as f:
docs = list(yaml.safe_load_all(f))
print(len(docs), 'documents')
for doc in docs:
for key, values in doc.items():
print(key, '->', ', '.join(values))
try:
with open('data.yaml') as f:
yaml.safe_load(f)
except yaml.YAMLError as e:
print(type(e).__name__)
The safe_load_all function returns a generator of documents; we
turn it into a list. The plain safe_load expects a single
document and raises ComposerError, a subclass of
yaml.YAMLError, for this file.
$ python read_docs.py 2 documents cities -> Bratislava, Kosice, Trnava companies -> Eset, Slovnaft, Matador ComposerError
Dumping data
The yaml.safe_dump function serializes a Python object into a
YAML string.
#!/usr/bin/python
import yaml
users = [{'name': 'John Doe', 'occupation': 'gardener', 'tags': ['a', 'b']},
{'name': 'Lucy Black', 'occupation': 'teacher', 'tags': []}]
print(yaml.safe_dump(users))
print(yaml.safe_dump(users, sort_keys=False))
print(yaml.safe_dump(users, sort_keys=False, default_flow_style=None))
By default, PyYAML sorts the keys of mappings; sort_keys=False
keeps the insertion order. All collections are written in block style. With
default_flow_style=None, collections that contain only scalars,
such as the tags, are written in flow style.
$ python dumping.py - name: John Doe occupation: gardener tags: - a - b - name: Lucy Black occupation: teacher tags: [] - name: John Doe occupation: gardener tags: - a - b - name: Lucy Black occupation: teacher tags: [] - name: John Doe occupation: gardener tags: [a, b] - name: Lucy Black occupation: teacher tags: []
Dump options
The dumper quotes strings that would otherwise load as a different type. A few options control the output further.
#!/usr/bin/python
import yaml
data = {'city': 'Žilina', 'note': 'it: has a colon', 'zip': '01001',
'empty': '', 'flag': 'yes', 'ratio': 0.5, 'none': None,
'servers': [{'host': 'a', 'port': 80}]}
print(yaml.safe_dump(data, sort_keys=False))
print(yaml.safe_dump(data, sort_keys=False, allow_unicode=True,
indent=4, width=60))
The strings 01001, yes, and the empty string are
quoted, so they load back as strings; so is the note with a colon. Without
allow_unicode=True, the letter Ž is written as an
escape sequence. The indent option sets the indentation of
nested mappings; width sets the preferred line width.
$ python dump_options.py
city: "\u017Dilina"
note: 'it: has a colon'
zip: '01001'
empty: ''
flag: 'yes'
ratio: 0.5
none: null
servers:
- host: a
port: 80
city: Žilina
note: 'it: has a colon'
zip: '01001'
empty: ''
flag: 'yes'
ratio: 0.5
none: null
servers:
- host: a
port: 80
Writing a file
When a file object is given as the second argument, safe_dump
writes to the file instead of returning a string.
#!/usr/bin/python
import yaml
users = [{'name': 'John Doe', 'occupation': 'gardener'},
{'name': 'Lucy Black', 'occupation': 'teacher'}]
with open('users_out.yaml', 'w', encoding='utf-8') as f:
yaml.safe_dump(users, f, sort_keys=False)
with open('users_out.yaml', encoding='utf-8') as f:
print(f.read())
with open('users_out.yaml', encoding='utf-8') as f:
print(yaml.safe_load(f) == users)
We write the list of users to a file, print the file, and load it again. The loaded data is equal to the original, so the round trip loses nothing for these types. Opening the file with an explicit encoding is good practice.
$ python writing.py - name: John Doe occupation: gardener - name: Lucy Black occupation: teacher True
Block scalars
Long and multi-line strings are written as block scalars. The literal style
| keeps line breaks; the folded style > joins
lines with spaces.
#!/usr/bin/python
import yaml
document = '''
literal: |
Line one
Line two
folded: >
This long sentence is
folded into one line.
stripped: |-
no final newline
'''
data = yaml.safe_load(document)
for key, value in data.items():
print(f'{key}: {value!r}')
Both styles end the string with a single newline by default. The
- indicator in |- removes it, and |+
would keep all trailing newlines. Block scalars are common for shell scripts
and long messages in configuration files.
$ python block_scalars.py literal: 'Line one\nLine two\n' folded: 'This long sentence is folded into one line.\n' stripped: 'no final newline'
Anchors, aliases, and merge keys
An anchor (&name) marks a node so that it can be reused with
an alias (*name). The merge key << copies the
entries of a mapping into another one.
#!/usr/bin/python
import yaml
document = '''
defaults: &defaults
adapter: postgresql
host: localhost
pool: 5
development:
<<: *defaults
database: dev_db
test:
<<: *defaults
database: test_db
pool: 2
'''
config = yaml.safe_load(document)
print(config['development'])
print(config['test'])
shared = ['a', 'b']
print(yaml.safe_dump({'x': shared, 'y': shared}))
Both environments inherit the settings from defaults;
test overrides the pool size. Merge keys are a YAML 1.1 feature
that PyYAML supports. When dumping, PyYAML creates anchors itself if the same
object appears twice in the data, as with the shared list.
$ python anchors.py
{'adapter': 'postgresql', 'host': 'localhost', 'pool': 5, 'database': 'dev_db'}
{'adapter': 'postgresql', 'host': 'localhost', 'pool': 2, 'database': 'test_db'}
x: &id001
- a
- b
y: *id001
Unsafe loading
YAML tags can ask the loader to create arbitrary Python objects and even call
functions. That is why we always use safe_load for data that we
do not fully trust.
#!/usr/bin/python
import yaml
document = '!!python/object/apply:os.getcwd []'
try:
yaml.safe_load(document)
except yaml.YAMLError as e:
print(type(e).__name__)
print(e.problem)
try:
yaml.load(document)
except TypeError as e:
print('TypeError:', e)
print(yaml.unsafe_load(document))
The document asks to call os.getcwd. The safe loader refuses
with a ConstructorError. Since PyYAML 6, yaml.load
requires an explicit Loader argument. The
unsafe_load function runs the call; with a function such as
os.system, a malicious file could run any command.
$ python unsafe.py ConstructorError could not determine a constructor for the tag 'tag:yaml.org,2002:python/object/apply:os.getcwd' TypeError: load() missing 1 required positional argument: 'Loader' /home/user/python
Errors
Invalid YAML raises an exception derived from yaml.YAMLError.
Parser errors carry the position of the problem.
#!/usr/bin/python
import yaml
broken = '''
name: falcon
speed: 389
weight: 1.2
'''
try:
yaml.safe_load(broken)
except yaml.MarkedYAMLError as e:
print('problem:', e.problem)
mark = e.problem_mark
print(f'line {mark.line + 1}, column {mark.column + 1}')
try:
yaml.safe_load('items: [a, b')
except yaml.YAMLError as e:
print(e)
The indented weight line is read as a continuation of the
value 389, and the colon after it is not allowed inside a plain
scalar. The problem_mark attribute holds zero-based line and
column numbers, so we add one. Printing the exception gives a complete
message with the context and a pointer to the position.
$ python errors.py
problem: mapping values are not allowed here
line 4, column 9
while parsing a flow sequence
in "<unicode string>", line 1, column 8:
items: [a, b
^
expected ',' or ']', but got '<stream end>'
in "<unicode string>", line 1, column 13:
items: [a, b
^
Custom tags
We can teach the safe dumper and loader our own types with a representer and a constructor bound to a custom tag.
#!/usr/bin/python
from dataclasses import dataclass, asdict
import yaml
@dataclass
class Point:
x: int
y: int
def point_representer(dumper, point):
return dumper.represent_mapping('!Point', asdict(point))
def point_constructor(loader, node):
return Point(**loader.construct_mapping(node))
yaml.SafeDumper.add_representer(Point, point_representer)
yaml.SafeLoader.add_constructor('!Point', point_constructor)
shapes = {'line': [Point(0, 0), Point(3, 4)]}
text = yaml.safe_dump(shapes)
print(text)
data = yaml.safe_load(text)
print(data)
print(data == shapes)
The representer turns a Point into a mapping tagged
!Point; the constructor builds a Point from such a
mapping. We register them on SafeDumper and
SafeLoader, so the safe functions handle points while still
refusing the dangerous Python tags.
$ python custom_tags.py
line:
- !Point
x: 0
y: 0
- !Point
x: 3
y: 4
{'line': [Point(x=0, y=0), Point(x=3, y=4)]}
True
Loading a configuration
In the last example we load an application configuration, fill in default values, apply an environment variable, and validate the result.
name: shop debug: false server: port: 8080 log_level: info
The file sets only some of the options.
#!/usr/bin/python
import copy
import os
import yaml
DEFAULTS = {'debug': False, 'server': {'host': '127.0.0.1', 'port': 8000},
'log_level': 'warning'}
LEVELS = {'debug', 'info', 'warning', 'error'}
def merge(base, override):
result = copy.deepcopy(base)
for key, value in override.items():
if isinstance(value, dict) and isinstance(result.get(key), dict):
result[key] = merge(result[key], value)
else:
result[key] = value
return result
def load_config(path):
with open(path, encoding='utf-8') as f:
data = yaml.safe_load(f) or {}
if not isinstance(data, dict):
raise ValueError(f'{path}: top level must be a mapping')
config = merge(DEFAULTS, data)
if 'APP_PORT' in os.environ:
config['server']['port'] = int(os.environ['APP_PORT'])
if config['log_level'] not in LEVELS:
raise ValueError(f'unknown log level: {config["log_level"]}')
return config
config = load_config('app.yaml')
print(yaml.safe_dump(config, sort_keys=False))
os.environ['APP_PORT'] = '9090'
print(load_config('app.yaml')['server'])
The merge function combines nested dictionaries recursively, so
the file can set server.port without removing
server.host. It deep-copies the defaults so that later changes
do not modify the DEFAULTS dictionary. An empty file loads as
None, hence the or {}. The APP_PORT
environment variable overrides the port, and an unknown log level is
rejected.
$ python load_config.py
debug: false
server:
host: 127.0.0.1
port: 8080
log_level: info
name: shop
{'host': '127.0.0.1', 'port': 9090}
Source
In this article we have read and written YAML files with PyYAML. See also Python tomllib, Python configparser, Python CSV, and Python logging, which loads its configuration from YAML.
Author
List all Python tutorials.