How to convert ruamel.yaml to dict with Python3?

4.8k views Asked by At

I want a dict (or OrderedDict) from ruamel.yaml. I am using Python 3.8, happy to switch to 3.9 if that helps.

from ruamel.yaml import YAML
from collections import OrderedDict

with open(self.filename) as f:
    data = yaml.load(f)
    print(type(data))  # <class 'ruamel.yaml.comments.CommentedMapItemsView'>

    data = dict(yaml.load(f))
    print(type(data))  # <class 'dict_items'>

    data = yaml.load(f).items()  # AttributeError: 'NoneType' object has no attribute 'items'
1

There are 1 answers

5
KayD On BEST ANSWER

I tried it with this example,

from ruamel.yaml import YAML

with open("test.yaml") as f:
    yaml = YAML()
    data = yaml.load(f)
    print(type(data))
    print("all: ", data)
    print(dict(data)) 
    print(dict(data)['data']) 

test.yaml

---
data: name
test1:
  - name: name1

Output

<class 'ruamel.yaml.comments.CommentedMap'>
all:  ordereddict([('data', 'name'), ('test1', [ordereddict([('name', 'name1')])])])
{'data': 'name', 'test1': [ordereddict([('name', 'name1')])]}
name 

You need to load YAML into a variable before use it so, you will need to use data instead of yaml.load(f). It shows the error with print(dict(yaml.load(f)))

If you don't have to round-trip, alternatively you can use the safe loader:

from pathlib import Path
from ruamel.yaml import YAML

yaml = YAML(typ='safe', pure=True)
data = yaml.load(Path('test.yaml'))
print(type(data))

This will load all mappings as dicts and sequences as lists instead of more complicated types for round-tripping.