Here is a yaml file I have:
animal:
- dog:
- noise:
- "woof"
- food:
- "dog food"
- house:
- "dog house"
- cat:
- noise:
- "meow"
- food:
- "cat food"
- home:
- "cat tree"
Here is the code I use to convert yaml to dictionary:
import yaml, pprint
from pathlib import Path
def gen_vars(conf_file)
conf = yaml.safe_load(Path(config_file).read_text())
pprint.pprint(conf)
return
gen_vars('./conf.yaml')
But here is the output:
{'animal': [{'dog': [{'noise': ['woof']},
{'food': ['dog food']},
{'house': ['dog house']}]},
{'cat': [{'noise': ['meow']},
{'food': ['cat food']},
{'home': ['cat tree']}]}]
}
Problems I have with this output:
- Every value is in a list. I dont want that.
- Every key/value pair is in a dictionary. I dont want that.
- Every key and value are in single quotes. I dont want that. I want this instead:
{"animal": {"dog": {"noise": "woof",
"food": "dog food",
"house": "dog house"}},
{"cat": {"noise": "meow",
"food": "cat food",
"home": "cat tree"}}
}
Am I formatting my yaml incorrectly? How can I get this type of output?
EDIT:
I figured out how to remove nested lists with dictionaries for each key value pair. This post answered my question: Load yaml list as dictionary
Need to format without the -
animal:
dog:
noise:
"woof"
food:
"dog food"
house:
"dog house"
cat:
noise:
"meow"
food:
"cat food"
home:
"cat tree"
Output:
{'animal': {'cat': {'food': 'cat food', 'home': 'cat tree', 'noise': 'meow'},
'dog': {'food': 'dog food', 'house': 'dog house', 'noise': 'woof'}}
Still, is there a way to make all single quotes double without converting to a string and using replace("\'","\"")
?