[英]Dump a list in Python dict into YAML file as examples
我有一個 Python 字典,如下所示,我想將它轉儲到 YAML 文件中。 我想將這些示例轉儲為字符串示例列表而不是單個鍵( examples
后面有一個 pipe |
。我該怎么做?
data = {'version': '1.0',
'food': [{'category': 'japanese', 'examples': ['sushi', 'ramen', 'sashimi']},
{'category': 'chinese', 'examples': ['hotpot', 'noodle', 'fried rice']}]}
yaml.SafeDumper.ignore_aliases = lambda *args : True
with open('food.yml', 'w', encoding = "utf-8") as yaml_file:
dump = yaml.safe_dump(data,
default_flow_style=False,
allow_unicode=False,
encoding=None,
sort_keys=False,
line_break=10)
yaml_file.write(dump)
結果
version: '1.0'
food:
- category: japanese
examples:
- sushi
- ramen
- sashimi
- category: chinese
examples:
- hotpot
- noodle
- fried rice
預期的
version: '1.0'
food:
- category: japanese
examples: |
- sushi
- ramen
- sashimi
- category: chinese
examples: |
- hotpot
- noodle
- fried rice
帶有|
的構造是文字樣式標量。 並且在其縮進的上下文中,前導破折號沒有特殊含義(即不被解析為塊樣式序列指示符)。 PyYAML 不支持在不添加表示器的情況下在單個字符串上使用這些文字標量。
PyYAML only supports a subset of YAML 1.1 and that specification was superseded in 2009. The recommended extension for files containing YAML documents has been .yaml
since at least [September 2006]( https://web.archive.org/w eb/20060924190202 /http://yaml.org/faq.html)。
目前尚不清楚為什么要使用這些過時的庫和約定,但看起來是時候升級了:
import sys
import ruamel.yaml
def literal(*args):
# convert args to a multiline string that looks like block sequence
# convert to string in case non-strings were passed in
return ruamel.yaml.scalarstring.LiteralScalarString(
'- ' + '\n- '.join([str(x) for x in args]) + '\n'
)
data = {'version': '1.0',
'food': [{'category': 'japanese', 'examples': literal('sushi', 'ramen', 'sashimi')},
{'category': 'chinese', 'examples': literal('hotpot', 'noodle', 'fried rice')}]}
yaml = ruamel.yaml.YAML()
yaml.dump(data, sys.stdout)
這使:
version: '1.0'
food:
- category: japanese
examples: |
- sushi
- ramen
- sashimi
- category: chinese
examples: |
- hotpot
- noodle
- fried rice
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.