Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python parse yaml file

I have yaml file and I want to get specific set of key-value pairs. How I can do that?

DEV:
  A: "A_DEV_config.xml"
  B: "B_DEV_config.xml"
  C: "C_DEV_config.xml"
PROD:
  D: "D_PROD_config.xml"
  E: "E_PROD_config.xml"
  F: "E_PROD_config.xml"
OTHERS:
  G: "G_config.xml"
  H: "H_config.xml"
  K: "K_config.xml"

I want to get something like this:

if I check DEV == true:

output list of keys ->  A,B,C,G,H,K

if I check PROD == true:

output list of keys ->  D,E,F,G,H,K

As you may have noticed, I need to get OTHERS in both cases.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to use code:

stream = open(yml_file, 'r')
data = yaml.safe_load(stream)
print(data.get("DEV").keys())

But I don’t know how to concatenated it together

>Solution :

To concatenate the keys (DEV or PROD) with the keys from the OTHERS section, you need to define a function to fetch the keys based on the environment and concatenate with OTHERS either way.

Below I have written a function:

import yaml

with open(yml_file, 'r') as stream:
    data = yaml.safe_load(stream)

def get_keys(environment):
    env_keys = list(data.get(environment, {}).keys())
    others_keys = list(data.get("OTHERS", {}).keys())
    return env_keys + others_keys

if DEV == True:
    print(get_keys("DEV"))
elif PROD == True:
    print(get_keys("PROD"))

Hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading