I have a YAML file that goes as (just an example):
a:
b: 1
a:
b: 2
c: 1
a:
b: 3
I want to read this file, and do some stuff with b
s and c
s. The problem is that I can't read this file as a dictionary using yaml.load()
, since it will only give me {'a':{'b': 3 }}
. Instead, I want to read it as a list of dictionaries, i.e, I want the output to be something like:
[
{'a':{'b': 1 }},
{'a':{'b': 2, 'c': 1 }},
{'a':{'b': 3 }}
]
How can I achieve this? Thanks...
Use lists. Ansible playbooks use YAML lists to represent a list of items. You can express them in two ways, shown below. Each element in the list is represented in YAML as a new line with the same indentation, starting with - followed by a space.
We can read the YAML file using the PyYAML module's yaml. load() function. This function parse and converts a YAML object to a Python dictionary ( dict object). This process is known as Deserializing YAML into a Python.
Reading a key from YAML config file We can read the data using yaml. load() method which takes file pointer and Loader as parameters. FullLoader handles the conversion from YAML scalar values to the Python dictionary. The index [0] is used to select the tag we want to read.
The latest YAML specification (1.2, from 2009) is quite explicit that keys in a mapping cannot be duplicated:
The content of a mapping node is an unordered set of key: value node pairs, with the restriction that each of the keys is unique.
As presented your file is not a valid YAML file and loading it should give you
a DuplicateKeyError
.
Since you know what you want to get, the easiest way to see what YAML would load like that is to dump the data structure:
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
data = [
{'a':{'b': 1 }},
{'a':{'b': 2, 'c': 1 }},
{'a':{'b': 3 }}
]
yaml.dump(data, sys.stdout)
which gives:
- a:
b: 1
- a:
b: 2
c: 1
- a:
b: 3
Use the snippet below as YAML
a:
- b: 1
- b: 2
c: 1
- b: 3
And get this dict in python (no need to duplicate 'a')
{
"a": [
{
"b": 1
},
{
"c": 1,
"b": 2
},
{
"b": 3
}
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With