简体   繁体   English

Python 如何将嵌套字段添加到 Yaml 文件

[英]Python How to add nested fields to Yaml file

I need to modify a YAML file and add several fields.I am using the ruamel.yaml package.我需要修改 YAML 文件并添加几个字段。我正在使用 ruamel.yaml package。

First I load the YAML file:首先我加载 YAML 文件:

data = yaml.load(file_name)

I can easily add new simple fields, like-我可以轻松添加新的简单字段,例如-

data['prop1'] = "value1"

The problem I face is that I need to add a nested dictionary incorporate with array:我面临的问题是我需要添加一个嵌套字典并与数组合并:

prop2:
  prop3:
    - prop4:
        prop5:  "Some title" 
        prop6:  "Some more data"

I tried to define-我试图定义——

record_to_add = dict(prop2 = dict(prop3 = ['prop4']))

This is working, but when I try to add beneath it prop5 it fails-这是可行的,但是当我尝试在它下面添加 prop5 时,它失败了-

record_to_add = dict(prop2 = dict(prop3 = ['prop4'= dict(prop5 = "Value")]))

I get我明白了

SyntaxError: expression cannot contain assignment, perhaps you meant "=="? SyntaxError: 表达式不能包含赋值,也许你的意思是“==”?

What am I doing wrong?我究竟做错了什么?

The problem has little to do with ruamel.yaml .这个问题与ruamel.yaml几乎没有关系。 This:这个:

['prop4'= dict(prop5 = "Value")]

is invalid Python as a list ( [ ] ) expects comma separated values.无效 Python 作为列表 ( [ ] ) 需要逗号分隔值。 You would need to use something like:你需要使用类似的东西:

record_to_add = dict(prop2 = dict(prop3 = dict(prop4= [dict(prop5 = "Some title"), dict(prop6='Some more data'),])))

As your program is incomplete I am not sure if you are using the old API or not.由于您的程序不完整,我不确定您是否使用旧的 API。 Make sure to use确保使用

import ruamel.yaml
yaml = ruamel.yaml.YAML()

and not不是

import ruamel.yaml as yaml

Its because of having ['prop4'= <> ].Instead record_to_add = dict(prop2 = dict(prop3 = [dict(prop4 = dict(prop5 = "Value"))])) should work.这是因为有 ['prop4'= <> ].Instead record_to_add record_to_add = dict(prop2 = dict(prop3 = [dict(prop4 = dict(prop5 = "Value"))]))应该工作。

Another alternate would be,另一种选择是,

import yaml

data = {
     "prop1": {
         "prop3":
             [{ "prop4":
                   {
                       "prop5": "some title",
                       "prop6": "some more data"
                   }
             }]
     }
 }

with open(filename, 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM