Python将字典中列表以|块格式导出为YAML文件的实现方法
实现方案
核心逻辑分两步:
- 提前把所有
examples字段的列表,手动拼接成带-前缀的多行字符串,匹配你需要的块内列表格式 - 给PyYAML注册自定义字符串类型的表示器,强制这类多行字符串使用
|字面量块样式输出,避免被自动加引号、转义换行。
完整可运行代码:
import yaml # 自定义Literal字符串类型,标记需要用|块格式输出的字符串 class LiteralStr(str): pass # 给Dumper注册该类型的表示器,指定输出为块样式 def literal_str_representer(dumper, data): return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') yaml.SafeDumper.add_representer(LiteralStr, literal_str_representer) yaml.SafeDumper.ignore_aliases = lambda *args : True # 原始数据 data = {'version': '1.0', 'food': [{'category': 'japanese', 'examples': ['sushi', 'ramen', 'sashimi']}, {'category': 'chinese', 'examples': ['hotpot', 'noodle', 'fried rice']}]} # 预处理:把所有examples字段转成LiteralStr类型的多行块字符串 for food_item in data['food']: # 把列表项拼成每行带- 前缀的字符串 example_lines = [f"- {item}" for item in food_item['examples']] food_item['examples'] = LiteralStr('\n'.join(example_lines) + '\n') # 导出YAML with open('food.yml', 'w', encoding = "utf-8") as yaml_file: dump = yaml.safe_dump(data, default_flow_style=False, allow_unicode=True, encoding=None, sort_keys=False, line_break='\n') yaml_file.write(dump)
运行后生成的food.yml内容完全匹配预期:
version: '1.0' food: - category: japanese examples: | - sushi - ramen - sashimi - category: chinese examples: | - hotpot - noodle - fried rice
注意事项
- 拼接字符串末尾补
\n是为了符合YAML块标量的格式规范,避免解析时出现格式警告 - 如果你的数据存在多层嵌套的
examples字段,只需要在预处理阶段递归遍历找到对应字段,做同样的字符串转换即可,核心导出逻辑不需要修改 - 示例中把
allow_unicode参数设为True,如果内容包含非ASCII字符(比如中文)不会被转义成Unicode编码,可根据实际需求调整
内容的提问来源于stack exchange,提问作者Isaac
相关产品推荐
相关产品推荐

