将重复的键值对追加到YAML中的嵌套字典

时间:2018-09-06 01:34:39

标签: python python-2.7 yaml ruamel.yaml

我正在尝试通过python脚本将重复的key:value对附加到YAML文件中的嵌套字典中。以下是我为实现此目的而编写的代码片段:

import click
import ruamel.yaml

def organization():
    org_num = int(input("Please enter the number of organizations to be created: "))
    org_val = 0
    while org_val!= org_num:
        print ("")
        print("Please enter values to create Organizations")
        print ("")
        for org in range(org_num):
            organization.org_name = str(raw_input("Enter the Organization Name: "))
            organization.org_description = str(raw_input("Enter the Description of Organization: "))
            print ("")
            if click.confirm("Organization Name: "+ organization.org_name + "\nDescription: "+ organization.org_description + "\nIs this Correct?", default=True):
                if org_val == 0:
                    org_val = org_val + 1
                    yaml = ruamel.yaml.YAML()
                    org_data = dict(
                        organizations=dict(
                            name=organization.org_name,
                            description=organization.org_description,
                        )
                    )
                    with open('input.yml', 'a') as outfile:
                        yaml.indent(mapping=2, sequence=4, offset=2)
                        yaml.dump(org_data, outfile)

               else:
                   org_val = org_val + 1
                   yaml = ruamel.yaml.YAML()
                   org_data = dict(
                            name=organization.org_name,
                            description=organization.org_description,
                            )
                   with open('input.yml', 'r') as yamlfile:
                       cur_yaml = yaml.load(yamlfile)
                       cur_yaml['organizations'].update(org_data)

                   if cur_yaml:
                       with open('input.yml','w') as yamlfile:
                           yaml.indent(mapping=2, sequence=4, offset=2)
                           yaml.dump(cur_yaml, yamlfile)
    return organization.org_name, organization.org_description

organization()

在python脚本的末尾,我的input.yml文件应如下所示:

version: x.x.x
is_enterprise: 'true'
license: secrets/license.txt
organizations:
  -  description: xyz
     name: abc
  -  description: pqr
     name: def

但是,每次脚本运行时,它不会将值附加到组织,而是会覆盖它。

我也尝试使用附加而不是更新,但是出现以下错误:

  

AttributeError:“ CommentedMap”对象没有属性“ append”

该怎么办?

此外,由于我是开发新手,因此任何有关改进此代码的建议都将非常有帮助。

3 个答案:

答案 0 :(得分:0)

如果我理解正确,那么您想要的是reversed(list(enumerate(your_list)))

请注意,如果您多次运行该脚本,那么您将有多次相同的条目。

答案 1 :(得分:0)

使用RegisterNotification(20);//set the time you want to push notification 无效,因为密钥的值 update是一个序列,并以类似organizations的类型加载 list。因此,CommentedSeq-ing是正确的选择。

那是行不通的,因为您没有提供该输入,所以有点不清楚 您开始使用的代码,也没有进行append处理时使用的代码 append上的AttributeError

如果您拥有一个组织并添加另一个组织,那么这将起作用:

CommentedMap

这给出了:

import sys
import ruamel.yaml

yaml_str = """\
version: x.x.x
is_enterprise: 'true'
license: secrets/license.txt
organizations:
  -  description: xyz
     name: abc
"""

org_data = dict(
   description='pqr',
   name='def',
)

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=4, sequence=4, offset=2)

cur_yaml = yaml.load(yaml_str)
cur_yaml['organizations'].append(org_data)
yaml.dump(cur_yaml, sys.stdout)

如果您还没有组织,请确保您输入的YAML如下:

version: x.x.x
is_enterprise: 'true'
license: secrets/license.txt
organizations:
  - description: xyz
    name: abc
  - description: pqr
    name: def

在旧版本的Python上,不能保证添加数据中键的顺序。至 还要在旧版本上执行该命令:

version: x.x.x
is_enterprise: 'true'
license: secrets/license.txt
organizations: []

org_data = ruamel.yaml.comments.CommentedMap((('description', 'pqr'), ('name', 'def')))

答案 2 :(得分:0)

发现了问题,现在可以正常工作了。由于名称和描述是组织的列表对象,因此我在下面的代码中添加了[],它开始起作用。

org_data = dict(
    organizations=[dict(
        name=tower_organization.org_name,
        description=tower_organization.org_description,
    )
    ]
)

除了上述内容外,我猜附加操作也不起作用,因为连字符'-'作为标识的一部分从第一个对象中丢失了。修复上述代码后,append也可以正常工作。

谢谢大家的回答。

相关问题