Issue
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
Solution
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))
Answered By - Filip Müller
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.