我需要使用不带“-”的pyyaml将字典导出到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的标准吗?
答案 0 :(得分:1)
yaml转储正确地导出了数据结构。您有一本具有一个键和一个值的字典(export_dash_dict
)。一个键是dashboards
,其值是包含两个元素的列表。这两个元素是字典(我们在这里不介绍其内容,但是有两个键值对)。
您说要导出的数据结构不是具有一个键/值对的字典,其中值是一个列表,而是具有两个键-值对的字典。第一个键是Dashboard title 1
,其值是字典(有两个键/值对,在此不再赘述)。第二个键是Dashboard title 2
,其值是字典(同样,有两个我们将不详述的键值对)。
如果您想yaml.dump
编写这样的数据结构,则需要构造该数据结构。
答案 1 :(得分:0)
感谢torek,这是构建字典的正确方法:
export_dash_dict = {}
export_dash_dict["dashboards"] = {}
for dashboard in dashboards_to_export:
export_dash_dict["dashboards"][dashboard.title] = {}
export_dash_dict["dashboards"][dashboard.title]["owner"] = dashboard.owner.username
export_dash_dict["dashboards"][dashboard.title]["description"] = dashboard.description
final_yaml = yaml.dump(export_dash_dict, default_flow_style=False,default_style=None)