python - 从包含特殊字符(星号、符号、*、&)的 python 字典写入 YAML 文件

标签 python dictionary yaml config pyyaml

我有一个 YAML 文件,我需要将其导入 python,以某种方式处理它,然后再次导出为 YAML 文件。更准确地说,我将 YAML 配置文件作为字典导入,生成许多具有更改参数的文件,然后再次将它们全部写入 YAML 文件。

我面临的问题是参数前面有特殊字符 ($, &):例如*目标大小。

当我在 python 中使用字典时,此参数是字符串格式的字典值 ('*target_size')。当我写这个 dict 时,YAML 文件格式得到保留,即 '*target_size' 在生成的 YAML 文件中被引号包围。我需要的只是 *target_size,与原始文件中的相同。

我查看了 pyYaml 文档和其他资源,但没有找到解决方案。

编写YAML文件的代码:

    with open(f'{PATH}/base_config.yml', 'w') as outfile:
         yaml.dump(config, outfile, default_flow_style=False, sort_keys=False)

original YAML python dict resulting file

最佳答案

不带引号的星号(*)和符号(&)是YAML中的特殊字符,代表aliases and anchors .它们让 YAML 文档的一部分引用 YAML 文档的另一部分。

当您将 YAML 文档反序列化为 Python 数据结构时,您会丢失有关原始文档中存在的 anchor 和别名的任何信息。

当您将 Python 数据结构序列化为 YAML 时,yaml 模块将在适当的地方自动生成 anchor 和别名来表示自引用数据结构。例如,鉴于此:

>>> import yaml
>>> doc = {'a': {'example': 'this is a test'}}
>>> doc['b'] = doc['a']
>>> print(yaml.safe_dump(doc))

我们看到以下输出:

a: &id001
  example: this is a test
b: *id001

您将无法使用标准 Python yaml 模块在反序列化/序列化管道中保留这些内容。

关于python - 从包含特殊字符(星号、符号、*、&)的 python 字典写入 YAML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61396981/

相关文章:

google-cloud-platform - Ansible 中的复杂数据结构

python - BeautifulSoup 使用一个查询找到所有多个类

python - 如何获得一周前的推文(使用 tweepy 或其他 python 库)

Python:从一月到当月动态选择列

c#-4.0 - 如何从 Dictionary<string,string> 中删除空元素?

ruby-on-rails - 在 Rails 中缓存 yaml 文件

python - Tensorflow InvalidArgumentError : indices[40] = 2000 0 is not in [0, 20000)

ios - 快速 JSON 错误字典?我该怎么办

英语词典sql数据库

amazon-web-services - 如何获取其他地区的ssm参数?