将Python字典转换为yam

2024-09-27 00:23:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典,我正在使用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$'
            }]
        }
    }]
}

我试过了:

^{pr2}$

我正在获取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$}和{}变得像{}。意思是内在的 词典内容不会转换为yaml。在

我也试过了

output_data = eval(json.dumps(output_data)) 
ff = open('meta.yaml', 'w+')
yaml.dump(output_data, ff, allow_unicode=True)

但是得到相同的yaml文件内容。在

如何在Python中将完整的dictionary转换为yaml?在


Tags: zoneyamloutputdata字典typenetworkboot
1条回答
网友
1楼 · 发布于 2024-09-27 00:23:24

默认情况下,PyYAML根据集合是否有嵌套集合来选择其样式。如果集合具有嵌套集合,则将为其指定块样式。否则它将具有流样式。在

如果希望集合始终以块样式序列化,请将dump()的参数default_flow_style设置为False。例如

> `print(yaml.dump(yaml.load(document), default_flow_style=False))`
>> Result: `a: 1 b:   c: 3   d: 4`

文档:https://pyyaml.org/wiki/PyYAMLDocumentation

相关问题 更多 >

    热门问题