【问题标题】:Need help to create complex yaml with python需要帮助使用 python 创建复杂的 yaml
【发布时间】:2021-11-30 07:36:09
【问题描述】:

我有以下代码

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 部分的帮助,我可以在那里添加我的字典列表

【问题讨论】:

  • 除了sources,你还发现了什么?到目前为止,您能向我们展示您的代码吗?

标签: python pyyaml


【解决方案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}}
)

【讨论】:

    【解决方案2】:

    Python 的yaml 模块允许您将字典数据转储为 yaml 格式:

    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)
    

    来自 yaml 的内容:

    services:
      name: testyaml
      os: Linux
      sources:
      - source: news
        target: industry
      - source: testing
        target: computer
      version: '2.5'
    

    【讨论】:

    • 能否请您看看我的问题,并特别查看我想如何展示这一点的来源,我已经使用了上面的代码。如果您看到我的 yaml 示例,则有“-”,然后在新行中出现源和目标
    • 我看到了@UmarDraz。以下答案为我提供了一些方向 - 但我无法为您找到一个好的解决方案。 stackoverflow.com/a/44284819/3786245
    • 我觉得挺难的,周围也没什么线索
    • 您可以编写自己的编码器...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    相关资源
    最近更新 更多