import yaml
output = [
'{"football": "basketball"}',
'{"basketball": "basketball" }'
]
dict_file = [
{'sports' : output},
{'countries' : [
'Pakistan',
'USA',
'India',
'China',
'Germany',
'France',
'Spain']
}
]
with open(r'E:\data\store_file.yaml', 'w') as file:
documents = yaml.dump(dict_file, file)
Output:
- sports:
- '{"football": "basketball"}'
- '{"basketball": "basketball" }'
Desired output:
- sports:
- {"football": "basketball"}
- {"basketball": "basketball" }
Please help me out.
CodePudding user response:
The YAML file accurately represents the data you've shown in your question. The variable output is a list of strings, not a list of dictionaries. For the desired output, you would need to fix your code:
output = [{"football": "basketball"}, {"basketball": "basketball" }]
Note that this will give you:
- sports:
- football: basketball
- basketball: basketball
Which is syntactically identical to:
- sports:
- {"football": "basketball"}
- {"basketball": "basketball" }
CodePudding user response:
You are storing strings in output
Remove the single quotes to make them dictionaries:
output = [{"football": "basketball"}, {"basketball": "basketball" }]
CodePudding user response:
ultimately, this can work for you
import yaml
import json
output = ['{"football": "basketball"}', '{"basketball": "basketball" }']
dict_file = [{'sports' : [json.loads(_) for _ in output]},
{'countries' : ['Pakistan', 'USA', 'India', 'China', 'Germany', 'France', 'Spain']}]
with open(r'E:\data\store_file.yaml', 'w') as file:
documents = yaml.dump(dict_file, file)
.yml file:
- sports:
- football: basketball
- basketball: basketball
- countries:
- Pakistan
- USA
- India
- China
- Germany
- France
- Spain
For your information, the dict structure will not come with {} brackets in the .yml. It will be without brackets and when reading you can read as a keys & values(Dict) type.
Note: Updated the answer and thanks for suggesting @accdias
