【发布时间】:2019-02-28 10:22:28
【问题描述】:
我需要用不带“-”的pyyaml将dict导出到yaml
export_dash_dict = {}
export_dash_dict["dashboards"] = []
for dashboard in dashboards_to_export:
single_dashboard = {}
single_dashboard[dashboard.title] = {}
single_dashboard[dashboard.title]["owner"] = dashboard.owner.username
single_dashboard[dashboard.title]["description"] = dashboard.description
export_dash_dict["dashboards"].append(single_dashboard)
final_yaml = yaml.dump(export_dash_dict, default_flow_style=False,default_style=None)
这就是 pyyaml 导出我的字典的方式:
dashboards:
- Dashboard title 1:
description: First
owner: username1
- Dashboard title 2:
description: Second
owner: username2
使用在线解析,这是我得到的:
{
"dashboards": [
{
"Dashboard title 1": {
"owner": "username1",
"description": "First"
}
},
{
"Dashboard title 2": {
"owner": "username2",
"description": "Second"
}
}
]
}
但我需要这样的东西:
dashboards:
Dashboard title 1:
description: First
owner: username1
Dashboard title 2:
description: Second
owner: username2
使用在线解析器:
{
"dashboards": {
"Dashboard title 2": {
"owner": "username2",
"description": "Second"
},
"Dashboard title 1": {
"owner": "username1",
"description": "First"
}
}
}
这样我在使用 yaml.load 时可以避免整个层级的数据
我正在使用:default_flow_style=False 参数,但我找不到避免“-”的方法 这是 YAML 的标准吗?
【问题讨论】:
-
您不应该使用
yaml.load(),它被记录为可能不安全。 onine 解析器没有显示你想要的输出列表,那么如果你不想要它们,为什么要首先在你的程序中创建它们呢?