How can I put the anchor to its item with python ruamel.yaml?

I have this format YAML file,

A: true
B:
- &C
  tag1: value1
  tag2: value2
- &D
  tag1: value3
  tag2: value4

I want to convert it to the format below, add name field with anchor.

A: true
B:
- &C
  tag1: value1
  tag2: value2
  name: C
- &D
  tag1: value3
  tag2: value4
  name: D

I am not sure if it’s possible. How can I do this?

Answer

The anchor information is stored in the anchor attribute, it has a field value which you should read, and a field always_dump which you will need to set if you want the anchors to appear without any aliases referring to them:

import sys
import ruamel.yaml

yaml_str = """
A: true
B:
- &C
  tag1: value1
  tag2: value2
- &D
  tag1: value3
  tag2: value4
"""

yaml = ruamel.yaml.YAML()
# yaml.indent(mapping=4, sequence=4, offset=2)
# yaml.preserve_quotes = True
data = yaml.load(yaml_str)
for mapping in data['B']:
    mapping['name'] = mapping.anchor.value
    mapping.anchor.always_dump = True
yaml.dump(data, sys.stdout)

which gives:

A: true
B:
- &C
  tag1: value1
  tag2: value2
  name: C
- &D
  tag1: value3
  tag2: value4
  name: D

If you don’t know where the anchors might show up in your data structure, you’ll have to recursively walk the values of dicts and elements of lists to do the above.