Home > Net >  Nested yaml - read only specific key values and always include top level values
Nested yaml - read only specific key values and always include top level values

Time:07-26

I have this yaml:

global:
  environment:
    DURATION: 3599
    BLA: 1234
    dev1:
      BASEPATH: bla.co.uk
      LOGGING: ERROR
    dev2:
      BASEPATH: bla.co.uk
      LOGGING: ERROR

Using the below will retrieve the dict for dev1.

import yaml

if __name__ == '__main__':

    stream = open("devtest.yaml", 'r')
    dictionary = yaml.load(stream)
    for key, value in dictionary["global"]["environment"]["dev1"].items():
        print (key   " : "   str(value))

I would like to get the environment: key values too on the way. Not just dev1. I can do it separately but then everything gets included under environment such as dev1 and dev2. I always want environment and either dev1 or dev2 upon choice.

Thanks

CodePudding user response:

You can go through the environment and check if the values are dictionaries or just simple values. Then you can only print the dictionary ones if they are the dev you want. This will, however, not work properly if there are other dict values that you would like to print.

def print_values(dictionary, dev: str):
    # dev is either "dev1" or "dev2"
    for key, value in dictionary["global"]["environment"].items():
        if not isinstance(value, dict):
            # if the value is not a dict, print it
            print (key   " : "   str(value))
            continue
        # if it is a dict, check if it is the dev you want,
        # print values inside if it is
        if key == dev:
            for dev_key, dev_value in value.items():
                print (dev_key   " : "   str(dev_value))

CodePudding user response:

You could write a method that accepts an environment of your choice and retrieves the properties from the yaml file. Then you could print the properties while also printing out the environment name.

Also, it is better to open files using with so that you don't need to remember to close them.

import yaml
 
def retrieve_env_properties(env_name):
    with open("devtest.yaml", 'r') as stream:
        dictionary = yaml.load(stream, Loader=yaml.Loader)
        return dictionary["global"]["environment"][env_name]

def print_env_properties(dictionary, env_choice):
    for key, value in dictionary.items():
        print (f"{env_choice}: {key} : {str(value)}")

if __name__ == '__main__':
    env_choice = "dev1"
    dictionary = retrieve_env_properties(env_choice)
    print_env_properties(dictionary, env_choice)
  • Related