Search code examples
pythondictionarynestedyaml

Python: nested dict and specification in one key


I need to make a yaml file with a dict and a specific format.
The desired format of the yaml file would be:

classification:
- type: 4
  probability: 1.0

So far I created a dict with the following:

dic = {
    'classification': {
        'type': 4,
        'probability': 1.0
    }

which creates the following yaml file:

classification:
  type: 4
  probability: 1.0

What do I need to do to get the - in front of type?


Solution

  • If you're using PyYAML, the hyphen gets added to the output for items within a list, so if you had:

    dic = {
        'classification': [  # start a list
            {
                'type': 4,
                'probability': 1.0
            }
        ]
    }
    

    then the output would be:

    import yaml
    
    yaml.dump(dic, sys.stdout)
    
    classification:
    - probability: 1.0
      type: 4
    

    Note that YAML seems to sort the dictionary keys alphabetically by default. To have it not sort the keys, you would instead do:

    yaml.dump(dic, sys.stdout, sort_keys=False))
    
    classification:
    - type: 4
      probability: 1.0