Insert a key using Ruamel
<p>I am using the Ruamel Python library to programmatically edit human-edited YAML files.  The source files have keys that are sorted alphabetically.</p>

<p>I'm not sure if this is a basic Python question, or a Ruamel question, but all methods I have tried to sort Ruamel's OrderedDict structure are failing for me.</p>

<p>I am quite confused, for instance, why the following code, based on <a href="https://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes" rel="nofollow noreferrer">this recipe</a>, isn't working:</p>

<pre class="lang-python prettyprint-override"><code>import ruamel.yaml
import collections

def read_file(f):
    with open(f, 'r') as _f:
        return ruamel.yaml.round_trip_load(
            _f.read(),
            preserve_quotes=True
        )

def write_file(f, data):
    with open(f, 'w') as _f:
        _f.write(ruamel.yaml.dump(
            data,
            Dumper=ruamel.yaml.RoundTripDumper,
            explicit_start=True,
            width=1024
        ))

data = read_file('in.yaml')
data = collections.OrderedDict(sorted(data.items(), key=lambda t: t[0]))
write_file('out.yaml', data)
</code></pre>

<p>But given this input file:</p>

<pre><code>---
bananas: 1
apples: 2
</code></pre>

<p>The following output file is produced:</p>

<pre><code>--- !!omap
- apples: 2
- bananas: 1
</code></pre>

<p>I.e. it's turned my file into a YAML ordered map.</p>

<p>Is there an easy way to do this?  Also, can I simply insert into the data structure somehow?</p>