You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python yaml.dump生成的YAML中description值带单引号?

问题:如何让YAML输出中所有description字段的值带单引号?

我有如下Python字典:

my_dict = {
    'table': { 
        'description': 'Table 1',
        'columns': [
            {'name': 'Column1', 'description': 'first column'},
            {'name': 'Column2', 'description': 'second column'},
            {'name': 'Column3', 'description': 'third column'}
        ]
    }
}

使用yaml.dump写入文件后,生成的YAML内容中description的值没有单引号:

table:
  description: Table 1
  columns:
  - name: Column1
    description: first column
  - name: Column2
    description: second column
  - name: Column3
    description: third column

希望得到的效果是所有description的值都被单引号包裹:

table:
  description: 'Table 1'
  columns:
  - name: Column1
    description: 'first column'
  - name: Column2
    description: 'second column'
  - name: Column3
    description: 'third column'

解决方案

可以利用PyYAML提供的SingleQuotedScalarString类型,手动标记需要单引号包裹的字符串,再递归遍历字典处理所有description字段:

步骤1:导入必要模块

import yaml
from yaml.scalarstring import SingleQuotedScalarString

步骤2:编写递归处理函数

这个函数会遍历字典和列表,找到所有键为description的值,将其转换为单引号字符串类型:

def wrap_descriptions_in_quotes(obj):
    if isinstance(obj, dict):
        for key, value in obj.items():
            if key == 'description':
                obj[key] = SingleQuotedScalarString(value)
            else:
                wrap_descriptions_in_quotes(value)
    elif isinstance(obj, list):
        for item in obj:
            wrap_descriptions_in_quotes(item)

步骤3:处理字典并写入YAML

# 处理字典中的所有description字段
wrap_descriptions_in_quotes(my_dict)

# 写入文件
with open('Table1.yaml', 'w') as f:
    yaml.dump(my_dict, f)

执行以上代码后,生成的YAML文件就会符合预期,所有description的值都会被单引号包裹。


内容的提问来源于stack exchange,提问作者Hiwot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 03:45:43