[英]Access nested elements in YAML and output ordered unique python list
I am trying to parse a yaml-file to output the nested child-elements into an ordered unique python list, which does not include duplicate values.我正在尝试将 yaml 文件解析为 output 嵌套的子元素到有序的唯一 python 列表中,该列表不包含重复值。 My input yaml-file is:
我的输入 yaml 文件是:
# example.yml
name_1:
parameters:
- soccer
- football
- basketball
- cricket
- hockey
- table tennis
tag:
- navigation
assets:
- url
name_2:
parameters:
- soccer
- rugby
- swimming
examples:
- use case 1
- use case 2
- use case 3
I managed to print out the first child of all the parents, which are:我设法打印出所有父母的第一个孩子,它们是:
['assets', 'examples', 'parameters', 'tag']
with the following code:使用以下代码:
import yaml
with open(r'/Users/.../example.yml') as file:
documents = yaml.full_load(file)
a_list = []
for item, doc in documents.items():
a_list.extend(doc)
res = list(set(a_list))
res.sort()
print(res)
I am struggling to extend the script to obtain the following ordered unique list below the parameters
-element:我正在努力扩展脚本以获取
parameters
- 元素下方的以下有序唯一列表:
['basketball', 'cricket', 'football', 'hockey', 'rugby', 'soccer', 'swimming', 'table tennis']
Thanks in advance for any suggestions!在此先感谢您的任何建议!
I was able to get this by iterating the parameters
key -我能够通过迭代
parameters
键来得到这个 -
import yaml
with open(r'example.yaml') as file:
documents = yaml.full_load(file)
a_list = []
a_vals=[]
for item, doc, in documents.items():
for val in doc['parameters']:
a_vals.append(val)
a_list.extend(doc)
res = list(set(a_list))
res.sort()
a_vals=list(set(a_vals))
a_vals.sort()
print(a_vals)
print(res)
Output - Output -
python.exe "pysuperclass.py"
['basketball', 'cricket', 'football', 'hockey', 'rugby', 'soccer', 'swimming', 'table tennis']
['assets', 'examples', 'parameters', 'tag']
You don't need the intermediate lists, just add to a set directly.您不需要中间列表,只需直接添加到集合中即可。
import yaml
with open("example.yml") as fh:
documents = yaml.full_load(fh)
params = set()
for key in documents.keys():
params.update(documents[key]["parameters"])
print(sorted(params))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.