【问题标题】:Formatting yaml to include a nested dictionary?格式化 yaml 以包含嵌套字典?
【发布时间】:2020-05-03 12:50:22
【问题描述】:

对不起,如果这是一个愚蠢的问题,我对 yaml 配置(通常是 + 配置)非常陌生,一切都有些混乱。我有一个这样的文件:

hosts:
  - hostid: 43842
    tag: "name"
    items:
      port: "some port"
      in: 2342124
      out: 2349334
  - hostid: 24586
    tag: "..."

等等。此配置适用于我的项目(用 python 制作),但我想在“项目”下添加更多端口值,并让它们有自己的输入/输出坐标。我似乎找不到合适的格式。有什么方法可以解决这个问题?提前谢谢你。

【问题讨论】:

    标签: python configuration yaml


    【解决方案1】:

    您可以在项目中包含对象列表。多个端口。

    hosts:
      - hostid: 43842
        tag: "name"
        items:
          - port: "some port"
            in: 2342124
            out: 2349334
          - port: "some other port"
            in: 2342124
            out: 2349334
    

    或者如果你想在同一个端口下有多个输入/输出值,你可以在某个属性下添加一个列表,例如数据

    hosts:
      - hostid: 43842
        tag: "name"
        items:
          port: "some port"
          data:
            - in: 2342124
              out: 2349334
            - in: 2342124
              out: 2349334
    

    【讨论】:

      【解决方案2】:

      看起来items 是dict 类型,这意味着您不能拥有相同的键,或者您一遍又一遍地覆盖值。您需要的是 list 或 dicts。

      我们可以使用pyyaml (pip install pyyaml) 来完成此操作。这是一个例子

      import yaml
      
      contents = """
      hosts:
        - hostid: 43842
          tag: "name"
          items:
            port: "some port"
            in: 2342124
            out: 2349334"""
      
      # cook the data a little to make items a list instead of a dict
      data = yaml.full_load(contents)
      for d in data.get('hosts'):
          d['items'] = [d.get('items')]
      
      # modify whatever we are interested in
      for host in data.get('hosts'):
          if host.get('hostid') == 43842:
              host['items'].append({
                  'port': 'another port',
                  'in': 12345,
                  'out': 12345
              })
      
      # show our modifications
      print(yaml.dump(data))
      

      打印出来:

      hosts:
      - hostid: 43842
        items:
        - in: 2342124
          out: 2349334
          port: some port
        - in: 12345
          out: 12345
          port: another port
        tag: name
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-14
        • 1970-01-01
        • 2021-04-09
        • 1970-01-01
        • 1970-01-01
        • 2012-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多