Python字典使用PyYaml进入yaml文档

时间:2013-01-01 16:25:58

标签: python yaml pyyaml

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

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

yaml文件应如下所示:

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

-- !action
run: yes
print: no
report: maybe
...

使用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

以下是如何使用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)

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

2 个答案:

答案 0 :(得分: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

提醒一句,词典是无序的,因此无法保证您生成的YAML的顺序。如果您想在房子里订购 - 请查看OrderedDict

答案 1 :(得分:1)

怎么样:

class Bunch(yaml.YAMLObject):
    yaml_tag = u'!Bunch'
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        return '{c}({a})'.format(
            c = self.__class__.__name__,
            a = ', '.join(
                ['='.join(map(str,item)) for item in self.__dict__.items()]))
tag_names = ['define', 'action']
namespace = {}
for name in tag_names:
    namespace[name] = type(name, (Bunch,), {'yaml_tag':u'!{n}'.format(n = name)})

definitions = {"one" : 1, "two" : 2, "three" : 3}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}
text = yaml.dump_all([namespace['define'](**definitions),
                      namespace['action'](**actions)],
                     default_flow_style = False,
                     explicit_start = True)
print(text)

产生

--- !define
one: 1
three: 3
two: 2
--- !action
print: 'no'
report: maybe
run: 'yes'

将YAML加载回Python对象:

for item in  yaml.load_all(text):
    print(item)
    # define(one=1, three=3, two=2)
    # action(print=no, report=maybe, run=yes)

YAMLObject的子类用于创建application-specific tags.