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'
I tried it with this example,
test.yaml
Output
You need to load YAML into a variable before use it so, you will need to use
data
instead ofyaml.load(f)
. It shows the error withprint(dict(yaml.load(f)))
If you don't have to round-trip, alternatively you can use the safe loader:
This will load all mappings as
dict
s and sequences aslist
s instead of more complicated types for round-tripping.