Consider the following file YAML file:
A:
&B
- x: 1
y: 2
- x: 10
y: 20
C:
<<: *B
which is read into python via:
from ruamel.yaml import YAML
filename = 'data/configs/debug_config.yml'
with open(filename) as f:
c = YAML(typ='safe').load(f)
print(c)
yielding:
{'A': [{'x': 1, 'y': 2}, {'x': 10, 'y': 20}], 'C': {'x': 1, 'y': 2}}
It is seen that the anchor B
only includes the first element of the sequence. Why? I would like an anchor that would include the entire sequence, such that the values of A
and C
in the python dictionary are identical. How can this be done?
The anchor B
includes all elements from A
, but you are merging them with the merge key <<
(source):
If the value associated with the merge key is a sequence, then this sequence is expected to contain mapping nodes and each of these nodes is merged in turn according to its order in the sequence. Keys in mapping nodes earlier in the sequence override keys specified in later mapping nodes.
So,the first item from A
overrides the second one.
Remove <<:
and C
will be the same dictionary as A
:
A: &B
- x: 1
y: 2
- x: 10
y: 20
C: *B
Yields:
{
"A": [
{
"y": 2,
"x": 1
},
{
"y": 20,
"x": 10
}
],
"C": [
{
"y": 2,
"x": 1
},
{
"y": 20,
"x": 10
}
]
}
You can check the merge order with this example:
A: &B
- x: 1
y: 2
- x: 10
new: 333
C:
<<: *B
Yields:
{
"A": [
{
"y": 2,
"x": 1
},
{
"x": 10,
"new": 333
}
],
"C": {
"y": 2,
"x": 1,
"new": 333
}
}