将Python字典转换为Yaml

Har*_*ani 4 python dictionary yaml

我有一个字典,我正在使用yamlpython中的模块将字典转换为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$'
            }]
        }
    }]
}
Run Code Online (Sandbox Code Playgroud)

我试过了 :

import yaml
f = open('meta.yaml', 'w+')
yaml.dump(output_data, f, allow_unicode=True)
Run Code Online (Sandbox Code Playgroud)

我正在获取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
Run Code Online (Sandbox Code Playgroud)

在这里,{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)
Run Code Online (Sandbox Code Playgroud)

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

如何在Python中将完整的字典转换为Yaml?

小智 6

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

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

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

说明文件:https : //pyyaml.org/wiki/PyYAMLDocumentation

  • 对于 Python 3.8+ 和 PyYAML 6.x,以下代码有效 `print(yaml.dump(document))` (3认同)