Yaml file:
tests:
test1:
one:
description:
- test one
method:
- runTestOne
two:
description:
- test two
method:
- runTestTwo
three:
description:
- test three
method:
- runTestThree
test2:
one:
description:
- test one
method:
- runTestOne
test3:
one:
description:
- teste one
method:
- runTestOne
yaml.py
import os
import pprint
import ruamel.yaml
from ruamel.yaml.scanner import ScannerError
yaml = ruamel.yaml.YAML()
if os.path.exists('test.yaml'):
with open('test.yaml', 'r', encoding='utf8') as file:
try:
dictionary = yaml.load(file)
except ScannerError as error:
print('Yaml file structure is invalid')
else:
print('Yaml file not exists')
pprint.pprint(dictionary['tests'])
dictionary print:
{'test1': {'one': {'description': ['test one'],
'method': ['runTestOne']},
'three': {'description': ['test three'],
'method': ['runTestThree']},
'two': {'description': ['test two'],
'method': ['runTestTwo']}},
'test2': {'one': {'description': ['test one'],
'method': ['runTestOne']}},
'test3': {'one': {'description': ['teste one'],
'method': ['runTestOne']}}}
I need iterate the dictionary, readed from a yaml file, to obtain the nodes names according with this example:
test1.one
test1.two
test1.three
test2.one
test3.one
I´m using Python 3.8.5
I've tried it in several ways, but I´ma Python newbie, and I couldn't come up with an implementation to resolve this.
I will be grateful for any help.
Regard´s
I believe you need a nested iteration on your dict
Demo:
dictionary = {'test1': {'one': {'description': ['test one'],
'method': ['runTestOne']},
'three': {'description': ['test three'],
'method': ['runTestThree']},
'two': {'description': ['test two'],
'method': ['runTestTwo']}},
'test2': {'one': {'description': ['test one'],
'method': ['runTestOne']}},
'test3': {'one': {'description': ['teste one'],
'method': ['runTestOne']}}}
for k,v in dictionary.items():
for m, n in v.items():
node = f"{k}.{m}"
print(node)
Output:
test1.one
test1.three
test1.two
test2.one
test3.one
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.