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

如何在Python字典YAML序列化后仅为值添加单引号

Solution: Force Single-Quoted Values (No Quoted Keys)

Got it, let's tackle this problem head-on! The core issue here is that the default yaml.dump() behavior doesn't let you quote only values—either numbers stay unquoted, or using default_style adds quotes to keys too, which you don't want.

The fix is to create a custom YAML representer that forces all values (regardless of their original type) to be serialized as single-quoted strings, while leaving keys untouched. Here's how to do it:

Step-by-Step Code Implementation

import yaml
from yaml.representer import Representer

# Define a custom representer to output all values as single-quoted strings
def represent_single_quoted_value(dumper, data):
    # Convert the value to a string first, then wrap it in single quotes
    return dumper.represent_scalar('tag:yaml.org,2002:str', str(data), style="'")

# Register this representer for all the data types you need to handle
# Start with common types: strings, integers, floats
Representer.add_representer(str, represent_single_quoted_value)
Representer.add_representer(int, represent_single_quoted_value)
Representer.add_representer(float, represent_single_quoted_value)

# Optional: Add more types if you need them (e.g., booleans, None)
# Representer.add_representer(bool, represent_single_quoted_value)
# Representer.add_representer(type(None), represent_single_quoted_value)

# Your original dictionary
theDict = {'this' : {'is': 'the', 'main': 12,'problem':'see?' }}

# Dump the YAML with your custom rules
print(yaml.dump(theDict, default_flow_style=False, sort_keys=False))

Expected Output

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

How This Works

  • The custom represent_single_quoted_value function converts any input value to a string and tells the YAML dumper to wrap it in single quotes.
  • By registering this function for specific data types (like int, str), we ensure every value of those types gets quoted.
  • Keys use YAML's default serialization rules, so they never get quoted (unless they contain special characters, which your example doesn't have).

If you have other data types in your dictionary (like booleans or None), just add their representer registrations as shown in the commented lines.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 17:55:37