[Python] Convert Python dictionary to yaml

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dictionary, I am converting dictionary to yaml using yaml module in python. But Yaml is not converting properly.

    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)


    I am getting meta.yaml file as following:

    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$} are written like a dictionary. It means inner dictionary contents are not converting to yaml.

    I also tried,

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


    But getting same yaml file content.

    How can I convert a nested dictionary into yaml in Python?

    Continue reading...

Compartilhe esta Página