如何在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_valuefunction 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
相关产品推荐
相关产品推荐

