PyYAML用下划线替换键中的破折号

时间:2014-02-08 19:35:02

标签: python yaml

我想直接将YAML中的一些配置参数映射到Python参数名称。只是想知道是否有一种方法可以不编写额外代码(以后修改密钥)让YAML解析器用带有下划线'_'的键替换短划线' - '。

some-parameter: xyz
some-other-parameter: 123

当使用PyYAML(或可能是其他lib)解析具有值的字典时,应该成为:

{'some_parameter': 'xyz', 'some_other_parameter': 123}

我可以将字典作为命名参数传递给函数:

foo(**parsed_data)

我知道我之后可以遍历键并修改它们的值,但我不想这样做:)

3 个答案:

答案 0 :(得分:3)

至少在您说明的情况下,您无需转换密钥。给出:

import pprint

def foo(**kwargs):
    print 'KWARGS:', pprint.pformat(kwargs)

如果你设置:

values = {
    'some-parameter': 'xyz',
    'some-other-parameter': 123,
}

然后致电:

foo(**values)

你得到:

KWARGS: {'some-other-parameter': 123, 'some-parameter': 'xyz'}

如果你的目标是实际调用这样的函数:

def foo(some_parameter=None, some_other_parameter=None):
    pass

然后确定,您需要映射关键名称。但你可以这样做:

foo(**dict((k.replace('-','_'),v) for k,v in values.items()))

答案 1 :(得分:0)

我想我找到了一个解决方案:有一个名为yconf的包:https://pypi.python.org/pypi/yconf

我可以使用众所周知的argparse-interface:

映射值并使用它

config.yml

logging:
  log-level: debug

Argparse之类的定义:

parser.add_argument("--log-level", dest="logging.log-level")

答案 2 :(得分:0)

好吧,如果您将YAML文件解析为python字典,则可以使用以下代码将所有破折号(在所有嵌套的字典和数组中)都转换为破折号。

def hyphen_to_underscore(dictionary):
"""
Takes an Array or dictionary and replace all the hyphen('-') in any of its keys with a underscore('_')
:param dictionary:
:return: the same object with all hyphens replaced by underscore
"""
# By default return the same object
final_dict = dictionary

# for Array perform this method on every object
if type(dictionary) is type([]):
    final_dict = []
    for item in dictionary:
        final_dict.append(hyphen_to_underscore(item))

# for dictionary traverse all the keys and replace hyphen with underscore
elif type(dictionary) is type({}):
    final_dict = {}
    for k, v in dictionary.items():
        # If there is a sub dictionary or an array perform this method of it recursively
        if type(dictionary[k]) is type({}) or type(dictionary[k]) is type([]):
            value = hyphen_to_underscore(v)
            final_dict[k.replace('-', '_')] = value
        else:
            final_dict[k.replace('-', '_')] = v

return final_dict

以下是示例用法

customer_information = {
"first-name":"Farhan",
"last-name":"Haider",
"address":[{
    "address-line-1": "Blue Mall",
    "address-line-2": None,
    "address-type": "Work"
},{
    "address-line-1": "DHA",
    "address-line-2": "24-H",
    "address-type": "Home"
}],
"driver_license":{
    "number": "209384092834",
    "state-region": "AB"
}
}

print(hyphen_to_underscore(customer_information))
# {'first_name': 'Farhan', 'last_name': 'Haider', 'address': [{'address_line_1': 'Blue Mall', 'address_line_2': None, 'address_type': 'Work'}, {'address_line_1': 'DHA', 'address_line_2': '24-H', 'address_type': 'Home'}], 'driver_license': {'number': '209384092834', 'state_region': 'AB'}}