'How can I keep the anchors and aliases as the are?

E.g. input file

username: &username john
password: &password  xyz
server: &servername 192.168.0.1
host:
 server: *servername
 username: *username
 password: *password

output file is showing null instead of the *servername *username *password, if O do yaml.dump

username: &username john
password: &password  xyz
server: &servername 192.168.0.1
host:
 server: null
 username: null
 password: null

reading like this

with open(file_name, 'r') as file: 
    loaded_data = yaml.safe_load(file) 

writing

with open('filename.yaml', 'w') as f: 
    data = yaml.dump(loaded_data, f, sort_keys=False,default_flow_style=False,allow_unicode = True, indent=2)


Solution 1:[1]

For round-trip (loading, changing, dumping) of YAML in Python I recommend using ruamel.yaml (disclaimer: I am the author of that package). It supports YAML 1.2, preserves comments and tags (even when tagging simple scalars as in your case), none of which PyYAML can do:

import sys
from pathlib import Path
import ruamel.yaml

in_file = Path('input.yaml')
yaml = ruamel.yaml.YAML()
yaml.indent(mapping=1)       # to match your input, default is 2
data = yaml.load(in_file)
yaml.dump(data, sys.stdout)  # replace sys.stdout with in_file to overwrite the input

which gives:

username: &username john
password: &password xyz
server: &servername 192.168.0.1
host:
 server: *servername
 username: *username
 password: *password

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anthon