Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill default parameters in yaml file using python

Tags:

python

yaml

I have a YAML file with content:

       image_name: ubuntu
       components:
                 image_name: ubuntu
                 image_flavors: [medium, large]
                 image_ip : 192.168.12.134
                 imageuser : ubuntu
                 image_pass : ubuntu
                 image_config: /home/ubuntu/
                 image_net_type: vlan 
                 image_switch_type: ovs

I have implemented a script for this to load YAML file and o/p I have got in dict format.

       with open("test.yaml", "r") as input:
        try:
            a = yaml.safe_load(input)
            print "Parsing YAML file is completed"
            print a
        except yaml.YAMLError as error:
            print(error)

my dict format as below:

{'image_name': 'ubuntu', 'components': {'image_ip': '192.168.12.134', 
 'image_pass': 'ubuntu', 'image_switch_type': 'ovs', 'imageuser': 'ubuntu',
 'image_name': 'ubuntu', 'image_flavors': ['medium', 'large'], 
 'image_net_type': 'vlan', 'image_config': '/home/ubuntu/'}}

How I can fill default parameters if any key has no values?

like image 318
Keerthi Sharma Avatar asked Sep 15 '25 18:09

Keerthi Sharma


1 Answers

One option is when you are getting a value for a key in the dict that was parsed from the yaml, use the get() method of the dict. so

value = a.get('key', 'default')

If the key key is in a it will return the value else it will return whatever you specify as the default. In the above e.g that would be 'default'

like image 193
WreckeR Avatar answered Sep 17 '25 08:09

WreckeR