Search code examples
python-3.xlistserializationpyyaml

How to serialize escaped strings in a list


I'm trying to a .yml policy document for AWS. The problem is my list of strings is being surrounded in double quotes "" when I try to escape it myself, i.e.
- "'acm:AddTagsToCertificate'".

When I do nothing, it shows as
- acm:AddTagsToCertificate.

Problem is I need the final result in the .yml to look like
- 'acm:AddTagsToCertificate'

In terms of my own trouble shooting, I've tried using double and single quotations. I've also tried subclassing list to override how lists are serialized until other SO answers said that was frowned upon.

Here's the reduced code which shows my issue

import yaml;

data = {'apigateway:CreateDeployment': 6}

actions = [];

for key in data:
  key = "\'" + key + "\'"
  print(key)
  actions.append(key);

with open('test.yml', 'w') as output:
  yaml.dump(actions, output, default_flow_style=False)

Solution

  • Use default_style="'" in the dump:

    import yaml
    
    data = {'apigateway:CreateDeployment': 6}
    
    actions = list(data.keys())
    
    with open('test.yml', 'w') as output:
      yaml.dump(actions, output, default_flow_style=False, default_style="'")