Python: nested dict and specification in one key

Question:

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?

Asked By: ndehler

||

Answers:

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
Answered By: Matt Pitkin
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.