Python字典使用PyYaml进入yaml文档

Per*_*nce 3 python yaml pyyaml

我有两个python词典,我想写一个yaml文件,有两个文件:

definitions = {"one" : 1, "two" : 2, "three" : 3}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}
Run Code Online (Sandbox Code Playgroud)

yaml文件应如下所示:

--- !define
one: 1
two: 2
three: 3

-- !action
run: yes
print: no
report: maybe
...
Run Code Online (Sandbox Code Playgroud)

使用PyYaml我没有找到明确的方法来做到这一点.我确信有一个简单的方法,但深入研究PyYaml文档,只会让我感到困惑.我需要自卸车,发射器还是什么?这些类型产生什么类型的输出?Yaml文字?yaml节点?YAMLObject?无论如何,如果有任何澄清,我将不胜感激.


按照下面unutbu的回答,这是我能提出的最简洁的版本:

DeriveYAMLObjectWithTag是一个创建新类的函数,该类派生自具有所需标记的YAMLObject:

def DeriveYAMLObjectWithTag(tag):
    def init_DeriveYAMLObjectWithTag(self, **kwargs):
        """ __init__ for the new class """
        self.__dict__.update(kwargs)

    new_class = type('YAMLObjectWithTag_'+tag,
                    (yaml.YAMLObject,),
                    {'yaml_tag' : '!{n}'.format(n = tag),
                    '__init__' :  init_DeriveYAMLObjectWithTag})
    return new_class
Run Code Online (Sandbox Code Playgroud)

以下是如何使用DeriveYAMLObjectWithTag获取所需的Yaml:

definitions = {"one" : 1, "two" : 2, "three" : 3, "four" : 4}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}
namespace = [DeriveYAMLObjectWithTag('define')(**definitions),
             DeriveYAMLObjectWithTag('action')(**actions)]

text = yaml.dump_all(namespace,
                     default_flow_style = False,
                     explicit_start = True)
Run Code Online (Sandbox Code Playgroud)

感谢所有回答的人.我似乎PyYaml缺乏功能,这是克服它的最优雅的方法.

fav*_*tti 7

好吧,我仍在调查自动注释(无法立即找到文档)但这应该可以解决问题:

import yaml

definitions = {"one" : 1, "two" : 2, "three" : 3}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}

output = yaml.dump(actions, default_flow_style=False, explicit_start=True)
output += yaml.dump(definitions, default_flow_style=False, explicit_start=True)

print output
Run Code Online (Sandbox Code Playgroud)

需要注意的是,词典是无序的,因此无法保证您生成的YAML的顺序.如果您想在房子里订购 - 请查看OrderedDict.