本文介绍了在 Python 中,如何将 YAML 映射加载为 OrderedDicts?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想让 PyYAML 的加载器将映射(和有序映射)加载到 Python 2.7+ 中OrderedDict 类型,而不是普通的 dict
以及它当前使用的配对列表.
I'd like to get PyYAML's loader to load mappings (and ordered mappings) into the Python 2.7+ OrderedDict type, instead of the vanilla dict
and the list of pairs it currently uses.
最好的方法是什么?
推荐答案
注意:有一个基于以下答案的库,它也实现了 CLoader 和 CDumpers:Phynix/yamlloader
Note: there is a library, based on the following answer, which implements also the CLoader and CDumpers: Phynix/yamlloader
我非常怀疑这是最好的方法,但这是我想出的方法,而且确实有效.也可作为要点.
I doubt very much that this is the best way to do it, but this is the way I came up with, and it does work. Also available 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
这篇关于在 Python 中,如何将 YAML 映射加载为 OrderedDicts?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!