How to configure ruamel.yaml.dump output?
<p>With this data structure:</p>

<pre><code>d = {
    (2,3,4): {
        'a': [1,2], 
        'b': 'Hello World!',
        'c': 'VoilÃ !'
    }
}
</code></pre>

<p>I would like to get this YAML:</p>

<pre><code>%YAML 1.2
---
[2,3,4]:
  a:
    - 1
    - 2
  b: Hello World!
  c: 'VoilÃ !'
</code></pre>

<p>Unfortunately I get this format:</p>

<pre><code>$ print ruamel.yaml.dump(d, default_flow_style=False, line_break=1, explicit_start=True, version=(1,2))
%YAML 1.2
---
? !!python/tuple
- 2
- 3
- 4
: a:
  - 1
  - 2
  b: Hello World!
  c: !!python/str 'VoilÃ !'
</code></pre>

<p>I cannot configure the output I want even with <code>safe_dump</code>. How can I do that without manual regex work on the output?</p>

<p>The only ugly solution I found is something like: </p>

<pre><code>def rep(x):
    return repr([int(y) for y in re.findall('^\??\s*-\s*(\d+)', x.group(0), re.M)]) + ":\n"
print re.sub('\?(\s*-\s*(\w+))+\s*:', rep, 
    ruamel.yaml.dump(d, default_flow_style=False, line_break=1, explicit_start=True, version=(1,2)))
</code></pre>

<p>You cannot get exactly what you want as output using  <code>ruamel.yaml.dump()</code> without major rework of the internals.</p>

<ul>
<li>The output you like has indentation 2 for the values of the top-level mapping (key <code>a</code>, <code>b</code>, etc) and indentation 4 for the elements of the sequence that is the value for the <code>a</code> key (with the <code>-</code> pushed in 2 positions. That would at least require differencing between indentation levels for mapping and sequences (if not for individual collections) and that is non-trivial.</li>
<li>Your sequence output is compacted from the <code>,</code> (comma, space) what a "normal" flow style emits to just a <code>,</code>. IIRC this cannot currently be influenced by any parameter, and since you have little contextual knowledge when emitting a collection, it is difficult to "not include the spaces when emitting a sequence that is a key". An additional option to <code>dump()</code> would require changes in several of the sources files and classes.</li>
</ul>

<p>Less difficult issues, with indication of solution:</p>

<ul>
<li>Your tuple has to magically convert to a sequence to get rid of the tag <code>!!python/tuple</code>. As you don't want to affect all tuples, this is IMO best done by making a subclass of <code>tuple</code> and represent this as a sequence (optionally represent such tuple as list only if actually used as a key). You can use <code>comments.CommentedKeySeq</code> for that (assuming <code>ruamel.yaml&gt;=0.12.14</code>, it has the proper representation support when using <code>ruamel.yaml.round_trip_dump()</code></li>
<li>Your key is, when tested before emitting, not a simple key and as such it get a '? ' (question mark, space) to indicate a complex mapping key. . You would have to change the emitter so that the <code>SequenceStartEvent</code> starts a simple key (if it has flow style and not block style). An additional issue is that such a SequenceStartEvent then will be "tested" to have a <code>style</code> attribute (which might indicate an explicit need for '?' on key). This requires changing <code>emitter.py:Emitter.check_simple_key()</code> and <code>emitter.py:Emitter.expect_block_mapping_key()</code>.</li>
<li>Your scalar string value for <code>c</code> gets quotes, whereas your scalar string value for <code>b</code> doesn't. You only can get that kind of difference in output in ruamel.yaml by making them different types. E.g. by making it type <code>scalarstring.SingleQuotedScalarString()</code> (and using <code>round_trip_dump()</code>).</li>
</ul>

<p>If you do:</p>

<pre><code>import sys
import ruamel.yaml
from ruamel.yaml.comments import CommentedMap, CommentedKeySeq
assert ruamel.yaml.version_info &gt;= (0, 12, 14)

data = CommentedMap()
data[CommentedKeySeq((2, 3, 4))] = cm = CommentedMap()
cm['a'] = [1, 2]
cm['b'] = 'Hello World!'
cm['c'] = ruamel.yaml.scalarstring.SingleQuotedScalarString('VoilÃ !')

ruamel.yaml.round_trip_dump(data, sys.stdout, explicit_start=True, version=(1, 2))
</code></pre>

<p>you will get:</p>

<pre><code>%YAML 1.2
---
[2, 3, 4]:
  a:
  - 1
  - 2
  b: Hello World!
  c: 'VoilÃ !'
</code></pre>

<p>which, apart from the now consistent indentation level of 2, the extra spaces in the flow style sequence, and the required use of the <code>round_trip_dump</code>, will get you as close to what you want without major rework. </p>

<p>Whether the above code is ugly as well or not is of course a matter of taste.</p>

<p>The output will, non-incidently, round-trip correctly when loaded using <code>ruamel.yaml.round_trip_load(preserve_quotes=True)</code>.</p>

<hr>

<p>If control over the quotes is not needed, and neither is the order of your mapping keys important, then you can also patch the normal dumper:</p>

<pre><code>def my_key_repr(self, data):
    if isinstance(data, tuple):
        print('data', data)
        return self.represent_sequence(u'tag:yaml.org,2002:seq', data,
                                       flow_style=True)
    return ruamel.yaml.representer.SafeRepresenter.represent_key(self, data)

ruamel.yaml.representer.Representer.represent_key = my_key_repr
</code></pre>

<p>Then you can use a normal sequence:</p>

<pre><code>data = {}
data[(2, 3, 4)] = cm = {}
cm['a'] = [1, 2]
cm['b'] = 'Hello World!'
cm['c'] = 'VoilÃ !'

ruamel.yaml.dump(data, sys.stdout, allow_unicode=True, explicit_start=True, version=(1, 2))
</code></pre>

<p>will give you:</p>

<pre><code>%YAML 1.2
---
[2, 3, 4]:
  a: [1, 2]
  b: Hello World!
  c: VoilÃ !
</code></pre>

<p>please note that you need to explicitly allow unicode in your output (default with <code>round_trip_dump()</code>) using <code>allow_unicode=True</code>. </p>

<hr>

<p>Â¹ <sub>Disclaimer: I am the author of <a href="https://pypi.python.org/pypi/ruamel.yaml" rel="nofollow">ruamel.yaml</a>.</sub></p>

python yaml ruamel.yaml