【发布时间】:2019-03-16 16:21:25
【问题描述】:
我有一本字典,我正在使用 python 中的yaml 模块将字典转换为 yaml。但是 Yaml 没有正确转换。
output_data = {
'resources': [{
'type': 'compute.v1.instance',
'name': 'vm-created-by-deployment-manager',
'properties': {
'disks': [{
'deviceName': '$disks_deviceName$',
'boot': '$disks_boot$',
'initializeParams': {
'sourceImage': '$disks_initializeParams_sourceImage$'
},
'autoDelete': '$disks_autoDelete$',
'type': '$disks_type$'
}],
'machineType': '$machineType$',
'zone': '$zone$',
'networkInterfaces': [{
'network': '$networkInterfaces_network$'
}]
}
}]
}
我试过了:
import yaml
f = open('meta.yaml', 'w+')
yaml.dump(output_data, f, allow_unicode=True)
我得到meta.yaml 文件如下:
resources:
- name: vm-created-by-deployment-manager
properties:
disks:
- autoDelete: $disks_autoDelete$
boot: $disks_boot$
deviceName: $disks_deviceName$
initializeParams: {sourceImage: $disks_initializeParams_sourceImage$}
type: $disks_type$
machineType: $machineType$
networkInterfaces:
- {network: $networkInterfaces_network$}
zone: $zone$
type: compute.v1.instance
在这里,{sourceImage: $disks_initializeParams_sourceImage$} 和 {network: $networkInterfaces_network$} 变得越来越像 dictionary。 意思是内在的
字典内容未转换为 yaml。
我也试过了,
output_data = eval(json.dumps(output_data))
ff = open('meta.yaml', 'w+')
yaml.dump(output_data, ff, allow_unicode=True)
但得到相同的yaml 文件内容。
如何在 Python 中将完整的字典转换为 yaml?
【问题讨论】:
-
yaml.dump(output_data, ff, allow_unicode=True, default_flow_style=False) -
@floydya :谢谢 .. 它奏效了。请写一个答案。这样我就可以接受并支持您的回答。
标签: python dictionary yaml