从字典创建 yaml python 在字典顶部添加 2 行

create yaml python from dict add 2 lines at top of dict

我正在努力创建一个具有一定灵活性的 yaml 配置文件。理想情况下,我需要创建一个包含字段的空白配置文件。

yaml 配置文件需要在最顶部有两个强制行。

这些是需要位于配置文件顶部的强制属性。

Component: "groups"
groups: 

但是我需要增加灵活性以允许用户指定他们想要添加的组数。他们可能需要 10 个,也可能需要 3 个。脚本将构建以下内容:

  group1:
    name: "Developers"
    description: "Developers"
    location: "US-East"
    code: "duse"
  group2:
    name: "QA"
    description: "QA"
    location: "US-West"
    code: "qawest"   
  group3:
    name: "Admin"
    description: "Admin"
    location: "US-Central"
    code: "acent" 

最终配置文件如下所示:

Component: "groups"
groups: 
  group1:
    name: "Developers"
    description: "Developers"
    location: "US-East"
    code: "duse"
  group2:
    name: "QA"
    description: "QA"
    location: "US-West"
    code: "qawest"   
  group3:
    name: "Admin"
    description: "Admin"
    location: "US-Central"
    code: "acent" 

挑战是我有以下脚本:

total_groups = int(input(f'How many total groups? \n'))
d = []
for i in range(0, total_groups):
    test = str(i)
    dtest = {
        'groups': {
            'group'+test: {
                'name': '',
                'desc': '',
                'loc': '',
                'code': ''
            }
        }
    }
    d.append(dtest)


print(yaml.dump(d, default_flow_style=False))

脚本的输出如下:

How many total groups? 
3
- groups:
    group0:
      code: ''
      desc: ''
      loc: ''
      name: ''
- groups:
    group1:
      code: ''
      desc: ''
      loc: ''
      name: ''
- groups:
    group2:
      code: ''
      desc: ''
      loc: ''
      name: ''

我需要删除 -groups: 并且只将它放在文件的顶部。我还需要弄清楚如何在文件顶部添加组件。我发现了以下内容,但似乎无法弄清楚如何进行这项工作。

>>> d = {}
>>> for i in range(0,5):
...      d.setdefault('result', [])
...      d['result'].append(i)

任何关于如何删除 -groups: 并将其与组件一起固定在脚本顶部的帮助:'groups' 将不胜感激。

关键(双关语)是在 YAML 文件中查看您想要的结构,并在 Python 中表示它。与其考虑这条线和那条线,不如考虑结构代表什么。对于所需的输出:

Component: "groups"
groups: 
  group1:
    name: "Developers"
    description: "Developers"
    location: "US-East"
    code: "duse"
  group2:
    name: "QA"
    description: "QA"
    location: "US-West"
    code: "qawest"   
  group3:
    name: "Admin"
    description: "Admin"
    location: "US-Central"
    code: "acent" 

数据是一个字典,有两个键:Component,其值是字符串groups,和groups,其值是另一个字典。换句话说,在 Python 中,它看起来像这样:

{
    'Component': 'groups',
    'groups': {
        'group1': {
            'name': 'Developers',
            'description': 'Developers',
            'location': 'US-East',
            'code': 'duse',
        },
        'group2': {
            'name': 'QA',
            'description': 'QA',
            'location': 'US-West',
            'code': 'qawest',
        },
        'group3': {
            'name': 'Admin',
            'description': 'Admin',
            'location': 'US-Central',
            'code': 'acent' ,
        },
    },
}

你可以这样构建:

import sys

from ruamel.yaml import YAML

# Initialize the YAML parser/dumper.
yaml = YAML()
yaml.default_flow_style = False

total_groups = int(input('How many total groups? \n'))

# Initialize a new dictionary to hold the groups.
groups = {}

for i in range(1, total_groups + 1):
    # Initialize a new dictionary for each group.
    group = {}

    print(f'Data for group #{i}')
    # Get the data for each group.
    for field in ['name', 'description', 'location', 'code']:
        group[field] = input(f'\tEnter {field}: ')
    
    # Add the new group's dictionary to the groups dictionary.
    groups[f'group{i}'] = group

# Create the top-level dictionary and insert groups.
data = {'Component': 'groups', 'groups': groups}

# Dump to stdout (which prints it).
yaml.dump(data, sys.stdout)

(我使用了 ruamel.yaml,这是你的一个标签,尽管你的代码使用了不同的格式——PyYAML,我想?两种方式都一样,真的。)

但是,我不确定这个数据结构是否理想; group1group2等本质上是无意义的键。我建议改为使用组的名称作为键,或者完全避开键并使用组的 list 而不是字典。 (请注意,使用名称作为键将要求所有名称都是唯一的。)