Skip to content Skip to sidebar Skip to footer

Remove Single Quotes From Dict Values While Adding Content To Yaml File Using Python Ruamel.yaml

I have an yaml file as mentioned below test1.yaml resources: name:{get_param: vname} ssh_keypair: {get_param: ssh_keypair} Now I want to add test1_routable_net: { get_param:

Solution 1:

In your program test is a string. Strings normally don't get quoted when dumped, but if their interpretation would be ambiguous, they will be. That is the reason why your output has the single quotes around them: to make sure that on reading back in this node is not incorrectly interpreted as a mapping instead of a string. Removing the non-existent quotes with .strip() therefore doesn't do anything.

You should work backwards from what you what you want to accomplish (you actually want a mapping instead of a string, as one can see from the output).

If you load your desired output, you will see that the value for test1_routable_net is a python dict (or a subclass thereof), so make sure that is what you assign to test:

import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
test = { 'get_param': 'abc_routable_net' }
with open('./test1.yaml') as fp:
    data = yaml.load(fp)
data['resources'].update({'test1_routable_net': test})

yaml.dump(data, sys.stdout)

Which gives:

resources:name:{get_param:vname}ssh_keypair: {get_param:ssh_keypair}
  test1_routable_net:get_param:abc_routable_net

This is semantically the same as your desired output, but since you want the get_param: abc_routable_net in flow-style, you could add:

yaml.default_flow_style=None

to get your desired output. You can also look at assigning, to test, a ruamel.comments.CommentedMap, which gives you more fine grained control over its style (and comments, etc.).

Solution 2:

"test" is not a string it is a dict: example:

import ruamel.yaml
import yaml
yaml = ruamel.yaml.YAML()
test={ 'get_param': 'abc_routable_net' }
with open('test1.yaml') as fp:
    data = yaml.load(fp)

data['resources'].update({'test1_routable_net':test})
yaml.dump(data,open('test2.yaml', 'w'))

Post a Comment for "Remove Single Quotes From Dict Values While Adding Content To Yaml File Using Python Ruamel.yaml"