Merge 如何在ruamel.yaml中将一个属性引用更改为锚点

Merge 如何在ruamel.yaml中将一个属性引用更改为锚点,merge,anchor,ruamel.yaml,Merge,Anchor,Ruamel.yaml,我在我的项目中使用了ruamel.yaml,并且有一个yaml文档使用了锚点,有多个地方引用了锚点。我想更改其中一个引用锚点的位置的属性之一,而不接触其他位置 下面的代码详细显示了我想要做的事情 yaml = ruamel.yaml.YAML() yaml_str = """\ foo: &foo color: red length: 599 weight: 32.3 bar: name: bar_one params: *foo a

我在我的项目中使用了ruamel.yaml,并且有一个yaml文档使用了锚点,有多个地方引用了锚点。我想更改其中一个引用锚点的位置的属性之一,而不接触其他位置

下面的代码详细显示了我想要做的事情

yaml = ruamel.yaml.YAML()
yaml_str = """\
foo: &foo
  color: red
  length: 599
  weight: 32.3

bar:
  name: bar_one
  params: *foo

anotherbar:
  name: bar_another
  params: *foo
"""
data = yaml.load(yaml_str)
data["anotherbar"]["params"]["length"] = 39
yaml.dump(data, sys.stdout)
将输出上述代码

foo: &foo
  color: red
  length: 39
  weight: 32.3

bar:
  name: bar_one
  params: *foo

anotherbar:
  name: bar_another
  params: *foo
我想更改“anotherbar”中的参数,但它也会更改“bar”

如果我在赋值之前复制参数,它会工作,但它也会复制我不想更改的其他参数:

data["anotherbar"]["params"] = data["anotherbar"]["params"].copy()
data["anotherbar"]["params"]["length"] = 39
yaml.dump(data, sys.stdout)
产出:

foo: &foo
  color: red
  length: 599
  weight: 32.3

bar:
  name: bar_one
  params: *foo

anotherbar:
  name: bar_another
  params:
    color: red
    length: 39
    weight: 32.3
但我实际上希望以下YAML没有任何重复:

foo: &foo
  color: red
  length: 599
  weight: 32.3

bar:
  name: bar_one
  params: *foo

anotherbar:
  name: bar_another
  params:
    <<: *foo
    length: 39
foo:&foo
颜色:红色
长度:599
体重:32.3
酒吧:
姓名:巴鲁一号
参数:*foo
另一条:
姓名:巴鲁
参数:

ruamel.yaml可以往返您想要的输出:

import sys
import io
import ruamel.yaml

yaml_str = """\
foo: &foo
  color: red
  length: 599
  weight: 32.3

anotherbar:
  name: bar_another
  params:
    <<: *foo
    length: 39
"""

yaml = ruamel.yaml.YAML()
buf = io.StringIO()
data = yaml.load(yaml_str)
yaml.dump(data, buf)
assert buf.getvalue() == yaml_str
foo: &foo
  color: red
  length: 599
  weight: 32.3

bar:
  name: bar_one
  params: *foo

anotherbar:
  name: bar_another
  params:
    <<: *foo
    length: 39
其中:

<class 'ruamel.yaml.comments.CommentedMap'>
[(0, ordereddict([('color', 'red'), ('length', 599), ('weight', 32.3)]))]
这给了你想要的:

import sys
import io
import ruamel.yaml

yaml_str = """\
foo: &foo
  color: red
  length: 599
  weight: 32.3

anotherbar:
  name: bar_another
  params:
    <<: *foo
    length: 39
"""

yaml = ruamel.yaml.YAML()
buf = io.StringIO()
data = yaml.load(yaml_str)
yaml.dump(data, buf)
assert buf.getvalue() == yaml_str
foo: &foo
  color: red
  length: 599
  weight: 32.3

bar:
  name: bar_one
  params: *foo

anotherbar:
  name: bar_another
  params:
    <<: *foo
    length: 39
foo:&foo
颜色:红色
长度:599
体重:32.3
酒吧:
姓名:巴鲁一号
参数:*foo
另一条:
姓名:巴鲁
参数: