1

I have the following code

name = "testyaml"
version = "2.5"
os = "Linux"
sources = [
     {
          'source': 'news', 
          'target': 'industry'
     }, 
     {
          'source': 'testing', 
          'target': 'computer'
     }
]

And I want to make this yaml with python3

services:
   name: name,
   version: version,
   operating_system: os,
   sources:
     -
      source: news
      target: industry
     -
      source: testing
      target: computer

I need a help specially on Sources part that how I can add my dictionary list there

Umar Draz
  • 131
  • 1
  • 3
  • 9

2 Answers2

1
import yaml

name = "testyaml"
version = "2.5"
os = "Linux"
sources = [
    {"source": "news", "target": "industry"},
    {"source": "testing", "target": "computer"},
]

yaml.dump(
    {"services": {"name": name, "version": version, "os": os, "sources": sources}}
)

Matteo Zanoni
  • 3,429
  • 9
  • 27
0

Python's yaml module allows you to dump dictionary data into yaml format:

import yaml

# Create a dictionary with your data
tmp_data = dict(
    services=dict(
        name=name,
        version=version,
        os=os,
        sources=sources
    )
)

if __name__ == '__main__':
    with open('my_yaml.yaml', 'w') as f:
        yaml.dump(tmp_data, f)

Contents from the yaml:

services:
  name: testyaml
  os: Linux
  sources:
  - source: news
    target: industry
  - source: testing
    target: computer
  version: '2.5'
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
  • would you please see my question and see the specially the sources that how I want to show that is something specially, I already using the above code. If you see my yaml example there is '-' and then in new line the source and target appears – Umar Draz Oct 11 '21 at 15:00
  • I see @UmarDraz. The following answer provided some direction to me – but I cannot find a good solution for you. https://stackoverflow.com/a/44284819/3786245 – Yaakov Bressler Oct 11 '21 at 16:14
  • 1
    I think it is quite difficult, and there is no clue around – Umar Draz Oct 11 '21 at 16:33
  • You could write your own encoder... – Yaakov Bressler Oct 11 '21 at 18:09