Python 格式化yaml以包含嵌套字典?

Python 格式化yaml以包含嵌套字典?,python,configuration,yaml,Python,Configuration,Yaml,很抱歉,如果这是一个愚蠢的问题,我对yaml配置(一般来说是配置)非常陌生,而且一切都有点混乱。我有一个这样的文件: hosts: - hostid: 43842 tag: "name" items: port: "some port" in: 2342124 out: 2349334 - hostid: 24586 tag: "..." 等等。此配置适用于我的项目(用python制作),但我想在“items”下添加一些端口值

很抱歉,如果这是一个愚蠢的问题,我对yaml配置(一般来说是配置)非常陌生,而且一切都有点混乱。我有一个这样的文件:

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

等等。此配置适用于我的项目(用python制作),但我想在“items”下添加一些端口值,并使它们具有自己的in/out坐标。我似乎找不到合适的格式。有哪些方法可以做到这一点?提前谢谢。

看起来像是
是一种
dict
类型,这意味着不能有相同的键,也不能反复覆盖值。您需要的是
目录的
列表

我们可以使用
pyyaml
pip安装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

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

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