0

I am generating an YAML file by dumping a dictionary in Python using yaml.dump function of the module 'pyyaml'. The following is my code where it dumps the dictionary to the YAML file.

with open('test.yaml', 'w') as outfile:
    yaml.dump(yaml_dict, outfile, default_flow_style=False, sort_keys=False)

The script above creates an YAML file that represents the scalar values (e.g. '5') with single quotes like the following

data:
- name: Name
  value: John
- name: Age
  value: '5'

However, I want the YAML file to represent the scalar values in double quotes. Desired output:

data:
- name: Name
  value: John
- name: Age
  value: "5"

How can I pass the dictionary to the YAML file in a way that the scalar values are represented with double quotes?

ambb
  • 41
  • 6
  • What YAML library are you using? Python doesn't have a `yaml` module in the std lib. – MattDMo Aug 12 '22 at 23:58
  • @MattDMo I am using `pyyaml` module – ambb Aug 13 '22 at 00:02
  • Does this answer your question? [PyYAML dump format](https://stackoverflow.com/questions/20805418/pyyaml-dump-format) – ljmc Aug 13 '22 at 10:06
  • One interesting question would be "why"; these are both equivalent in YAML... – Jiří Baum Aug 13 '22 at 11:31
  • You would have to create a string subclass that loads the single quoted string only and dumps it double quoted. This is not trivial in PyYAML as you need to change the input process in order not to loose the quoting information. In `ruamel.yaml` this is far more trivial to do. – Anthon Aug 14 '22 at 07:53

0 Answers0