import ruamel.yaml
yaml_str = """name:
  family: Smith   
  given: Alice    
"""
code = ruamel.yaml.round_trip_load(yaml_str)
code['name']['given'] = 'Bob'
ruamel.yaml.round_trip_dump(code, sys.stdout)
Save/dump a YAML file with comments in PyYAML