yaml python数组对象顺序



我正在试图找出一种保存我的yaml订单的方法吗?当我迭代词典时,我拿回订单是错误的。

from yaml import load
def __init__(self, logger, configFilePath):
    self.config_dict = None
    with open(configFilePath) as config:
        self.config_dict = load(config)
    logger.debug('values:')  
    for key, value in self.config_dict.iteritems():
        logger.debug('- ' + key + ': ' + str(value))
    logger.debug('+++ Successfully finished +++')
def getConfig(self):
    return self.config_dict    

yaml示例

    repos.images:
      -
       id: Thing1
       foo: bar 
       name: Sam
      -
       id: thing2
       foo: bar
       name: dan

这是我如何称呼课程的示例。它没有什么真正的幻想。简而

yamlObj = parser.config_parser(logger, theFile)
myYaml = yamlObj.getConfig()
for image in myYaml["repos.images"]:
    myStr = image["foo"] + '/' + image["id"]
    logger.debug("myStr is: " + myStr)

有没有办法做到这一点,或者有更好的方法可以构建yaml?

字典(或哈希,密钥/值,关联数组,地图,称其为您将要的内容(通常是无序的。如果您真的希望维护订单,则可以通过其他YAML库来实现这一目标(在工作中,我们使用https://pypi.python.org/pypi/ruamel.yaml使" In-"将"更新到yaml文件(。

,但是请确保还将有序的词典(Python3(或其他解决方案用于数据后,将其从YAML退出后。

您可以使用 namedtuple对加载配置有一定的控制。另外,考虑使用safe_load

import collections
import yaml

file = open("./so.yaml", 'r')
cfg = yaml.safe_load(file)
Config = collections.namedtuple("Config", ["id", "foo", "name"])
cfg_lst = [Config(**x) for x in cfg["repos.images"]]

,例如,

>>> print(cfg_lst)

会给你

>>> [Config(id='Thing1', foo='bar', name='Sam'), Config(id='thing2', foo='bar', name='dan')]

所以,要访问特定元素,例如,thing2,您将像这样

来访问它
>>> print(cfg_lst[1].id)
>>> thing2

我最近为此写了一个库, oyaml。在外壳上:

$ pip install oyaml

在您的Python代码中,这是一个字符更改:

from oyaml import load  # instead of `from yaml import load`

然后将映射加载到collections.OrderedDict实例中而不是常规dict中,从配置文件保存其原始订购。

最新更新