我正在编写python脚本,它可以使我的yaml工作自动化。我将从不同的csv文件创建一个yaml结构。但目前我正试图通过例子来理解yaml结构。我在看一些yaml教程和示例,遇到了一个需要正确解决的问题
对于上面的结构,我的python代码如下
import sys
import yaml
from collections import OrderedDict
d = {'version': '22-07-2017', 'description': 'energie balance',
'info': {
'principalInvestigator': 'Kalthoff',
'personInCharge': 'Scheer'
},
'dataSources': 'null',
'devices': {
'type': 'HMP',
'info': {
'description': 'temperature and humidity sensor',
'company': 'Vaisala',
'model': 'HMP35A',
},
'measures': {
'quantity': 'T',
'annotations': 'air',
'sensors': {
'number': '001',
'sources': {
'id': 'null',
'frequency': '0.1',
'aggregation': 'AVG',
'field': 'null'
}
}
}
}
}
with open('/home/ali/Desktop/yaml-conf-task/result.yml', 'w') as yaml_file:
yaml.dump(d, yaml_file, default_flow_style=False)
但当我打开yaml文件时,它会给我未排序的数据。我收到这个
^{pr2}$而不是得到这个
version: 21-07-2017
description: energie balance
info:
principalInvestigator: rob
personInCharge: rio
dataSources: null
devices:
- type: TMP
info:
description: temperature and humidity sensor
company: Vio
model: 35A
measures:
- quantity: T
annotation: air
sensors:
- number: 001
sources:
- id: null
frequency: 1
aggregation: AVG
field: null
如果有人建议我如何维持秩序,我将不胜感激。我查看了堆栈溢出,但无法解决问题。在
首先,从技术上讲,YAML是JSON的超集,因此,根据规范,不能保证映射集的顺序。因此,您要实现的并不是您能够在任何地方复制的东西,除非您控制了完整的数据流,否则您可能会遇到问题。在
另外,正如我在评论中所说的,Python自己的
dict
通常不是保序的,但是Python有collections.OrderedDict
,您可以重新声明您的结构以保持顺序为:是的,这比一个干净的}。在
dict
结构有点恶心,因为您必须使用嵌套的列表/元组来保持顺序,但是一旦您习惯了它,就不那么困难了—您只需要将所有的dict
声明替换为OrderedDict([])
,并将所有key: value
声明替换为{但这只是等式的一部分-一旦你有了一个保持其顺序的dict-like结构,你的YAML序列化程序也应该知道它。如果您只是通过一个通用的YAML序列化程序(假设是^{} )转储上述结构,您将得到:
^{pr2}$当然,它保持了顺序,但它导出了实际的内部
collections.OrderedDict
结构,允许您将其加载回相同的结构中,这不是您想要的。相反,您需要告诉它将您的OrderedDict
视为常规映射集,因此:现在,如果将其导出为:
您将获得:
相关问题 更多 >
编程相关推荐