将Python字典转换为yaml

问题描述 投票:0回答:2

我有一本字典,我正在使用 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?

python dictionary yaml
2个回答
27
投票

默认情况下,

PyYAML
根据集合是否具有嵌套集合来选择集合的样式。如果集合有嵌套集合,它将被分配块样式。不然就会有流动的风格。

如果希望集合始终以块样式序列化,请将 dump() 的参数

default_flow_style
设置为
False
。例如,

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

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


0
投票

在提出这个问题时,默认情况下是

default_flow_style=None
,但是 自 PyYaml 5.1 以来,默认情况下是
default_flow_style=False
,因此对于最新版本的 PyYaml,OP 的初始代码将产生所需的输出。

with open('meta.yaml', 'w+') as ff:
    yaml.dump(output_data, ff)

如果您想知道如何知道哪些参数有效,

dump
dump_all
的包装器,您可以使用
yaml.dump_all
,例如
help(yaml.dump_all)
显示所有有效参数。

上面的代码可以写成:

with open('meta.yaml', 'w+') as ff:
    yaml.dump_all([output_data], ff)
如果没有流通过,

dump_all
也可以返回字符串。

s = yaml.dump_all([output_data])
print(s)

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
© www.soinside.com 2019 - 2024. All rights reserved.