我有一个 python 有序字典,比如,
from collections import OrderedDict
a = OrderedDict()
a['name'] = 'hello'
a['msgs'] = ['hello', 'world']
我正在将它转换为 YAML 语法,
import yaml
with open("b.yaml", 'w') as stream:
stream.write(yaml.dump(a))
它打印,
!!python/object/apply:collections.OrderedDict
- - [name, hello]
- - msgs
- [hello, world]
然而,我希望有一个更简单的 YAML 格式,
name : hello
msgs:
- hello
- world
我如何强制 YAML 使用 hypen + space 符号而不是像 [a,b,c,d] 符号这样的 JSON 来打印列表项?
为什么 PyYAML 将 Ordered dict 项打印为 [name, hello] 而不是 name : hello?
请您参考如下方法:
您的问题混淆了一些事情。从您的初始示例开始,您需要显式编码以将您的 a = {...} 转换为 OrderedDict。抛开这些,这是您的预期输出:
>>> a = {
... "name" : 'hello',
... "msgs" : ['hello', 'world']
... }
>>> print(yaml.dump(a))
msgs: [hello, world]
name: hello
这不是您想要的。如果您阅读 FAQ特别是在这个问题上,你会发现将 default_flow_style 传递给 dump 会产生你想要的结果
>>> print(yaml.dump(a, default_flow_style=False))
msgs:
- hello
- world
name: hello
至于为什么OrderedDict会这样出来,这在YAML tags and Python types一节中有讨论。在文档中。简而言之,这样做是考虑到 Python 的 pickle 协议(protocol),并且由于 OrderedDict 在内部是 list(哪些 list 是有序的;dict 根据定义是无序的),它得到类似列表的表示。
