将Python字典转换为yaml

24 人关注

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

I tried :

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

Here, {sourceImage: $disks_initializeParams_sourceImage$} and {network: $networkInterfaces_network$} is getting like dictionary.这意味着内部 字典内容没有转换为yaml.

我也试过。

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

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

如何在Python中把完整的dictinary转换为yaml?

2 个评论
yaml.dump(output_data, ff, allow_unicode=True, default_flow_style=False)
@floydya : 谢谢 ......它成功了。请写一个答案。这样我就可以接受并给你的答案加分。
python
dictionary
yaml
Harsha Biyani
Harsha Biyani
发布于 2018-10-11
1 个回答
floydya
floydya
发布于 2018-10-11
已采纳
0 人赞同

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

如果你希望集合总是以块的方式被序列化,请将dump()的参数 default_flow_style 设置为 False 。比如说。

>> print(yaml.dump(yaml.load(document), default_flow_style=False))