title: I want to load a YAML file, possibly edit the data, and then dump it again. How can I preserve formatting?
body: <p><em>This question tries to collect information spread over questions about different languages and YAML implementations in a mostly language-agnostic manner.</em></p>
  
  <p>Suppose I have a YAML file like this:</p>
  
  <pre class="lang-yaml prettyprint-override"><code>first:
    - foo: {a: "b"}
    - "bar": [1, 2, 3]
  second: |   # some comment
    some long block scalar value
  </code></pre>
  
  <p>I want to load this file into an native data structure, possibly change or add some values, and dump it again. However, when I dump it, the original formatting is not preserved:</p>
  
  <ul>
  <li>The scalars are formatted differently, e.g. <code>"b"</code> loses its quotation marks, the value of <code>second</code> is not a literal block scalar anymore, etc.</li>
  <li>The collections are formatted differently, e.g. the mapping value of <code>foo</code> is written in block style instead of the given flow style, similarly the sequence value of <code>"bar"</code> is written in block style</li>
  <li>The order of mapping keys (e.g. <code>first</code>/<code>second</code>) changes</li>
  <li>The comment is gone</li>
  <li>The indentation level differs, e.g. the items in <code>first</code> are not indented anymore.</li>
  </ul>
  
  <p>How can I preserve the formatting of the original file?</p>