Python PyYAML用下划线替换短划线键
我想直接将一些配置参数从YAML映射到Python参数名中。只是想知道是否有一种方法不需要编写额外的代码(随后修改键),就可以让YAML解析器将键中的破折号“-”替换为下划线“-”Python PyYAML用下划线替换短划线键,python,yaml,Python,Yaml,我想直接将一些配置参数从YAML映射到Python参数名中。只是想知道是否有一种方法不需要编写额外的代码(随后修改键),就可以让YAML解析器将键中的破折号“-”替换为下划线“-” some-parameter: xyz some-other-parameter: 123 当使用PyYAML(或可能是其他库)解析时,应成为具有以下值的字典: {'some_parameter': 'xyz', 'some_other_parameter': 123} 然后我可以将字典作为命名参数传递给函数:
some-parameter: xyz
some-other-parameter: 123
当使用PyYAML(或可能是其他库)解析时,应成为具有以下值的字典:
{'some_parameter': 'xyz', 'some_other_parameter': 123}
然后我可以将字典作为命名参数传递给函数:
foo(**parsed_data)
我知道我可以在之后遍历这些键并修改它们的值,但我不想这样做:)至少在您声明的情况下,您不需要转换键。鉴于:
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()))
我想我找到了一个解决方案:有一个名为yconf的包: 我可以映射这些值,并使用著名的argparse接口使用它们: config.yml
logging:
log-level: debug
Argparse-like定义:
parser.add_argument("--log-level", dest="logging.log-level")
如果将YAML文件解析为python字典,那么可以使用以下代码将所有dash(在所有嵌套字典和数组中)转换为dash
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'}}
我的目标是使用第二种情况,并在config中免费获得所需的键=>无默认值。foo(**dict((k.replace('-','',v)表示k,v在values.items()中的值)=>这是我不想做的;),i、 e.后处理。我同意使用某种即时解决方案,其中一些lambda函数可能会在存储密钥之前转换密钥。。。