在Python中,如何将YAML映射加载为OrderedDicts?

时间:2011-02-25 19:52:12

标签: python dictionary serialization yaml pyyaml

我想让PyYAML的加载器将映射(和有序映射)加载到Python 2.7 + OrderedDict类型,而不是vanilla dict和列表它目前使用的对。

最好的方法是什么?

9 个答案:

答案 0 :(得分:131)

更新:在python 3.6+中,你可能根本不需要OrderedDict,因为在pypy中使用了new dict implementation已有一段时间了(尽管已经考虑过了)现在的CPython实现细节。

更新:在python 3.7+中, dict对象的插入顺序保存性质已被声明为Python语言规范的官方部分,请参阅{{ 3}}

我喜欢@James'What's New In Python 3.7,因为它简单。但是,它会更改默认的全局yaml.Loader类,这可能会导致麻烦的副作用。特别是,在编写库代码时,这是一个坏主意。此外,它不直接与yaml.safe_load()一起使用。

幸运的是,可以毫不费力地改进解决方案:

import yaml
from collections import OrderedDict

def ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
    class OrderedLoader(Loader):
        pass
    def construct_mapping(loader, node):
        loader.flatten_mapping(node)
        return object_pairs_hook(loader.construct_pairs(node))
    OrderedLoader.add_constructor(
        yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
        construct_mapping)
    return yaml.load(stream, OrderedLoader)

# usage example:
ordered_load(stream, yaml.SafeLoader)

对于序列化,我不知道一个明显的概括,但至少这不应该有任何副作用:

def ordered_dump(data, stream=None, Dumper=yaml.Dumper, **kwds):
    class OrderedDumper(Dumper):
        pass
    def _dict_representer(dumper, data):
        return dumper.represent_mapping(
            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
            data.items())
    OrderedDumper.add_representer(OrderedDict, _dict_representer)
    return yaml.dump(data, stream, OrderedDumper, **kwds)

# usage:
ordered_dump(data, Dumper=yaml.SafeDumper)

答案 1 :(得分:52)

yaml模块允许您指定自定义'representers'以将Python对象转换为文本,并指定'构造函数'以反转该过程。

_mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG

def dict_representer(dumper, data):
    return dumper.represent_dict(data.iteritems())

def dict_constructor(loader, node):
    return collections.OrderedDict(loader.construct_pairs(node))

yaml.add_representer(collections.OrderedDict, dict_representer)
yaml.add_constructor(_mapping_tag, dict_constructor)

答案 2 :(得分:33)

2018选项:

oyamlPyYAML的替代品,可以保留字典顺序。支持Python 2和Python 3。只需pip install oyaml,然后导入如下所示:

import oyaml as yaml

倾销/装载时,你不再会被搞砸的映射烦恼。

注意:我是oyaml的作者。

答案 3 :(得分:20)

2015(及更高版本)选项:

ruamel.yaml是PyYAML的替代品(免责声明:我是该软件包的作者)。保留映射的顺序是2015年第一版(0.1)中添加的内容之一。它不仅保留了词典的顺序,还保留了注释,锚名称,标签并支持YAML 1.2规范(2009年发布)

规范说不能保证排序,但是当然在YAML文件中有排序,并且适当的解析器可以保持这一点并透明地生成一个保持排序的对象。您只需选择正确的解析器,加载器和转储器¹:

import sys
from ruamel.yaml import YAML

yaml_str = """\
3: abc
conf:
    10: def
    3: gij     # h is missing
more:
- what
- else
"""

yaml = YAML()
data = yaml.load(yaml_str)
data['conf'][10] = 'klm'
data['conf'][3] = 'jig'
yaml.dump(data, sys.stdout)

会给你:

3: abc
conf:
  10: klm
  3: jig       # h is missing
more:
- what
- else

data的类型为CommentedMap,其功能类似于dict,但有额外的信息可以保留,直到被转储(包括保留的注释!)

答案 4 :(得分:15)

注意:有一个基于以下答案的库,它还实现了CLoader和CDumpers:Phynix/yamlloader

我非常怀疑这是最好的方法,但这是我提出的方式,它确实有效。也可以as a gist

import yaml
import yaml.constructor

try:
    # included in standard lib from Python 2.7
    from collections import OrderedDict
except ImportError:
    # try importing the backported drop-in replacement
    # it's available on PyPI
    from ordereddict import OrderedDict

class OrderedDictYAMLLoader(yaml.Loader):
    """
    A YAML loader that loads mappings into ordered dictionaries.
    """

    def __init__(self, *args, **kwargs):
        yaml.Loader.__init__(self, *args, **kwargs)

        self.add_constructor(u'tag:yaml.org,2002:map', type(self).construct_yaml_map)
        self.add_constructor(u'tag:yaml.org,2002:omap', type(self).construct_yaml_map)

    def construct_yaml_map(self, node):
        data = OrderedDict()
        yield data
        value = self.construct_mapping(node)
        data.update(value)

    def construct_mapping(self, node, deep=False):
        if isinstance(node, yaml.MappingNode):
            self.flatten_mapping(node)
        else:
            raise yaml.constructor.ConstructorError(None, None,
                'expected a mapping node, but found %s' % node.id, node.start_mark)

        mapping = OrderedDict()
        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            try:
                hash(key)
            except TypeError, exc:
                raise yaml.constructor.ConstructorError('while constructing a mapping',
                    node.start_mark, 'found unacceptable key (%s)' % exc, key_node.start_mark)
            value = self.construct_object(value_node, deep=deep)
            mapping[key] = value
        return mapping

答案 5 :(得分:10)

更新:不推荐使用该库,而使用yamlloader(基于yamlordereddictloader)

我刚刚发现了一个Python库(https://pypi.python.org/pypi/yamlordereddictloader/0.1.1),它是根据这个问题的答案创建的,并且使用起来非常简单:

db.execSQL("INSERT INTO POINTS_TABLE VALUES('NULL','NULL','NULL')");

答案 6 :(得分:4)

在我为Python 2.7安装PyYaml时,我更新了__init__.py,constructor.py和loader.py。现在支持load_pairs_hook选项用于加载命令。我所做的改变差异如下。

__init__.py

$ diff __init__.py Original
64c64
< def load(stream, Loader=Loader, **kwds):
---
> def load(stream, Loader=Loader):
69c69
<     loader = Loader(stream, **kwds)
---
>     loader = Loader(stream)
75c75
< def load_all(stream, Loader=Loader, **kwds):
---
> def load_all(stream, Loader=Loader):
80c80
<     loader = Loader(stream, **kwds)
---
>     loader = Loader(stream)

constructor.py

$ diff constructor.py Original
20,21c20
<     def __init__(self, object_pairs_hook=dict):
<         self.object_pairs_hook = object_pairs_hook
---
>     def __init__(self):
27,29d25
<     def create_object_hook(self):
<         return self.object_pairs_hook()
<
54,55c50,51
<         self.constructed_objects = self.create_object_hook()
<         self.recursive_objects = self.create_object_hook()
---
>         self.constructed_objects = {}
>         self.recursive_objects = {}
129c125
<         mapping = self.create_object_hook()
---
>         mapping = {}
400c396
<         data = self.create_object_hook()
---
>         data = {}
595c591
<             dictitems = self.create_object_hook()
---
>             dictitems = {}
602c598
<             dictitems = value.get('dictitems', self.create_object_hook())
---
>             dictitems = value.get('dictitems', {})

loader.py

$ diff loader.py Original
13c13
<     def __init__(self, stream, **constructKwds):
---
>     def __init__(self, stream):
18c18
<         BaseConstructor.__init__(self, **constructKwds)
---
>         BaseConstructor.__init__(self)
23c23
<     def __init__(self, stream, **constructKwds):
---
>     def __init__(self, stream):
28c28
<         SafeConstructor.__init__(self, **constructKwds)
---
>         SafeConstructor.__init__(self)
33c33
<     def __init__(self, stream, **constructKwds):
---
>     def __init__(self, stream):
38c38
<         Constructor.__init__(self, **constructKwds)
---
>         Constructor.__init__(self)

答案 7 :(得分:2)

5年前开放的主题有PyYAML ticket。它包含一些相关的链接,包括这个问题的链接:)我个人抓了gist 317164并稍微修改了一下来使用Python 2.7中的OrderedDict,而不是包含的实现(只是替换了类from collections import OrderedDict)。

答案 8 :(得分:0)

这是一个简单的解决方案,它还会检查地图中重复的顶级键。

import yaml
import re
from collections import OrderedDict

def yaml_load_od(fname):
    "load a yaml file as an OrderedDict"
    # detects any duped keys (fail on this) and preserves order of top level keys
    with open(fname, 'r') as f:
        lines = open(fname, "r").read().splitlines()
        top_keys = []
        duped_keys = []
        for line in lines:
            m = re.search(r'^([A-Za-z0-9_]+) *:', line)
            if m:
                if m.group(1) in top_keys:
                    duped_keys.append(m.group(1))
                else:
                    top_keys.append(m.group(1))
        if duped_keys:
            raise Exception('ERROR: duplicate keys: {}'.format(duped_keys))
    # 2nd pass to set up the OrderedDict
    with open(fname, 'r') as f:
        d_tmp = yaml.load(f)
    return OrderedDict([(key, d_tmp[key]) for key in top_keys])