【问题标题】:How to encase the value of a yaml in single quotes after a dictionary <> yaml serialization如何在字典 <> yaml 序列化后用单引号括起 yaml 的值
【发布时间】:2023-01-12 02:28:26
【问题描述】:

我想将我的字典转换为 yaml,其中键在不带引号的情况下呈现,但值用单引号引起来。

我找到了几种将键和值都包含在单引号中的解决方案,但这不是我想要的。您可以在下面看到一个示例脚本:

import yaml

theDict = {'this' : {'is': 'the', 'main': 12,'problem':'see?' }}

print(yaml.dump(theDict, default_flow_style=False, sort_keys=False))

这将输出:

this:
    is: the
    main: 12
    problem: see?

但是我想要:

this:
  is: 'the'
  main: '12'
  problem: 'see?'

【问题讨论】:

    标签: python yaml pyyaml


    【解决方案1】:

    如果你想要你的字符串被引用,你可以创建一个添加引号的自定义表示,如下所示:

    import yaml
    
    def quoted_presenter(dumper, data):
        return dumper.represent_scalar('tag:yaml.org,2002:str', data, style="'")
    
    yaml.add_representer(str, quoted_presenter)
    
    theDict = {'this' : {'is': 'the', 'main': 12,'problem':'see?' }}
    print(yaml.dump(theDict, default_flow_style=False, sort_keys=False))
    

    上面的代码产生这个输出:

    'this':
      'is': 'the'
      'main': 12
      'problem': 'see?'
    

    请注意,12不是引用因为它是一个整数,而不是一个字符串。如果你想引用它,你需要确保你的值是字符串:

    theDict = {'this' : {'is': 'the', 'main': '12','problem':'see?' }}
    

    或者,您可以注册第二个自动将整数值转换为字符串的表示器。

    【讨论】:

      猜你喜欢
      • 2017-03-15
      • 2021-01-30
      • 2021-08-02
      • 1970-01-01
      • 2021-06-26
      • 2012-05-24
      • 2022-12-04
      • 2020-11-16
      • 2021-05-13
      相关资源
      最近更新 更多