I have a YAML file with an unknown number of "layers", so when I load it to a Python dictionary it becomes a nested dictionary.
I don't want to allow keys without values in the YAML file. I'd like to either:
yaml.load()
if there are missing values, or None
values within the resulting nested dictionary.
import yaml
with open(input_path, "r") as yaml_file:
my_dict = yaml.load(yaml_file)
You can redefine the Parser
's process_empty_scalar
method to raise an error:
import yaml
yaml_str = """\
- 1
- - 2
-
- 3
"""
def pes(*args, **kw):
raise NotImplementedError
yaml.parser.Parser.process_empty_scalar = pes
data = yaml.safe_load(yaml_str)
print(data)
The above raises an error, if you comment out the assignment to .process_empty_scalar
it parses correct.
Please note:
dict
s will be formed.load
which is documented to be unsafe and almost guaranteed to be inappropriate.