Search code examples
pythondictionaryyamlpartial

Loading partial YAML into a dictionary


I have the following YAML configuration for each instance.

prod:
    login: A
    var1: VP1
    var2: VP2
QA:
   login: B
   var1: QP1
   var2: QP2

I want to load

  • Only QA block into a dictionary if my current environment is QA .
  • Only Prod block into dict, if my current environment is prod.

How can I conditionally load a block of YAML into a dict?

The downstream code is something like this

#bin/ksh
login = {login}
var1 = {var1}
var2 = {var2}

I want these values to be resolved in ksh script based on the environment.


Solution

  • Just load the entire file and then only grab the stuff under the key you want.

    with open('data.yml') as f:
        d = yaml.load(f.read())
        print yaml.dump(d['QA'])
    

    Something like that.