Search code examples
python-3.xdictionaryyamlpytestpyyaml

Load a yaml file and Iterate over a list in python


I have a yaml file with the below content:

testcases:
 - testcase_1:
    username:
    password:
 - testcase_2:
    username:
    password:  

How do I iterate through the over content. I want first to run testcases with the variables present inside testcases_1 and then later run testcases with variables in testcase_2. ? How do I do this ?///


Solution

  • You can use yaml.safe_load function to load the content and then you can iterate over it:

    import yaml
    
    content = None
    
    with open("D:/data.yml") as f:
        try:
            content = yaml.safe_load(f)
        except yaml.YAMLError as e:
            print(e)
    
    print(content)
    
    for item in content['testcases']:
        print(item)
    

    Above code will output:

    {'testcases': [{'testcase_1': {'username': None, 'password': None}}, {'testcase_2': {'username': None, 'password': None}}]}
    {'testcase_1': {'username': None, 'password': None}}
    {'testcase_2': {'username': None, 'password': None}}