0
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.

accdias
  • 5,160
  • 3
  • 19
  • 31

3 Answers3

0

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" }
larsks
  • 277,717
  • 41
  • 399
  • 399
0

You are storing strings in output

Remove the single quotes to make them dictionaries:

output = [{"football": "basketball"}, {"basketball": "basketball" }]
jfn
  • 2,486
  • 1
  • 13
  • 14
  • Thanks for the response. What if I have output like below? output = ['i prefer a [football]{"xyz": "sports", "val": "health"} than basketball'] – Shiva Sharan Jan 12 '22 at 14:10
0

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

Tamil Selvan
  • 1,600
  • 1
  • 9
  • 25