这并不容易。除非您要用于锚点的数据在节点内。这是因为锚点附加到节点内容,在您的示例中为“[1,2,3]”,并且不知道该值与键“a”相关联。
l = [1, 2, 3]
foo = {'a': l, 'b': l}
class SpecialAnchor(yaml.Dumper):
def generate_anchor(self, node):
print('Generating anchor for {}'.format(str(node)))
anchor = super().generate_anchor(node)
print('Generated "{}"'.format(anchor))
return anchor
y1 = yaml.dump(foo, Dumper=Anchor)
给你:
Generating anchor for SequenceNode(tag='tag:yaml.org,2002:seq', value=[ScalarNode(tag='tag:yaml.org,2002:int', value='1'), ScalarNode(tag='tag:yaml.org,2002:int', value='2'), ScalarNode(tag='tag:yaml.org,2002:int', value='3')])
Generated "id001"
a: &id001 [1, 2, 3]
b: *id001
到目前为止,我还没有找到一种方法来获取给定节点的密钥“a”......