gpt4 book ai didi

Python YAML 转储指针引用

转载 作者:行者123 更新时间:2023-12-01 09:15:46 30 4
gpt4 key购买 nike

我正在尝试使用几个组件模板构建 YAML 文档。我正在加载它们,构建一个 Python 对象,然后尝试将它们转储(最终转储到文件中,但此示例只是打印)。正如您在下面看到的,它打印引用和指针,而不是我期望的字符串数据。我做错了什么(或没有做什么)?

这是我用来演示我的问题的示例:

import yaml

main_template = yaml.load('organization: main')

sub_template = yaml.load('''
division: development
other:
data:
- for: users
''')

users = [ 'alice', 'bob', 'kim' ]

all_user_data = dict(main_template)

user_list = []

for user in users:
tmp = dict(sub_template)
tmp['name'] = user
user_list.append(tmp)

all_user_data['users'] = user_list
print(yaml.dump(all_user_data, default_flow_style=False))

这会产生:

organization: main
users:
- division: development
name: alice
other: &id001
data:
- for: users
- division: development
name: bob
other: *id001
- division: development
name: kim
other: *id001

我期待这样的输出:

organization: main
users:
- division: development
name: alice
other:
data:
- for: users
- division: development
name: bob
other:
data:
- for: users
- division: development
name: kim
other:
data:
- for: users

最佳答案

正如 Anthon 在 Avoid references in PyYAML 中所建议的那样,你可以这样做

yaml.Dumper.ignore_aliases = lambda *args : True

那么,

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

产量

organization: main
users:
- division: development
name: alice
other:
data:
- for: users
- division: development
name: bob
other:
data:
- for: users
- division: development
name: kim
other:
data:
- for: users

我不知道为什么会这样。感谢安东。

奥利弗

关于Python YAML 转储指针引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51272814/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com