Ankit Kumar
Ankit Kumar

Reputation: 1281

Read YAML file as list

I have a YAML file that goes as (just an example):

a:
    b: 1    
a:
    b: 2    
    c: 1
a:
    b: 3

I want to read this file, and do some stuff with bs and cs. The problem is that I can't read this file as a dictionary using yaml.load(), since it will only give me {'a':{'b': 3 }}. Instead, I want to read it as a list of dictionaries, i.e, I want the output to be something like:

[
    {'a':{'b': 1 }},
    {'a':{'b': 2, 'c': 1 }},
    {'a':{'b': 3 }}
]

How can I achieve this? Thanks...

Upvotes: 6

Views: 771

Answers (2)

Anthon
Anthon

Reputation: 76568

The latest YAML specification (1.2, from 2009) is quite explicit that keys in a mapping cannot be duplicated:

The content of a mapping node is an unordered set of key: value node pairs, with the restriction that each of the keys is unique.

As presented your file is not a valid YAML file and loading it should give you a DuplicateKeyError.

Since you know what you want to get, the easiest way to see what YAML would load like that is to dump the data structure:

import sys
import ruamel.yaml

yaml = ruamel.yaml.YAML()
data = [
    {'a':{'b': 1 }},
    {'a':{'b': 2, 'c': 1 }},
    {'a':{'b': 3 }}
]
yaml.dump(data, sys.stdout)

which gives:

- a:
    b: 1
- a:
    b: 2
    c: 1
- a:
    b: 3

Upvotes: 2

balderman
balderman

Reputation: 23815

Use the snippet below as YAML

a:
    - b: 1    
    - b: 2    
      c: 1
    - b: 3

And get this dict in python (no need to duplicate 'a')

{
  "a": [
    {
      "b": 1
    }, 
    {
      "c": 1, 
      "b": 2
    }, 
    {
      "b": 3
    }
  ]
}

Upvotes: 1

Related Questions