首页 > 解决方案 > 需要帮助使用 python 创建复杂的 yaml

问题描述

我有以下代码

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

我想用python3制作这个yaml

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

我需要特别在 Sources 部分的帮助,我可以在那里添加我的字典列表

标签: pythonpyyaml

解决方案


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}}
)


推荐阅读