【发布时间】:2018-02-09 03:59:10
【问题描述】:
我想要什么
从 yaml 配置中,我得到一个如下所示的 python 字典:
conf = {
'cc0': {
'subselect':
{'roi_spectra': [0], 'roi_x_pixel_spec': 'slice(400, 1200)'},
'spec':
{'subselect': {'x_property': 'wavenumber'}},
'trace':
{'subselect': {'something': 'jaja', 'roi_spectra': [1, 2]}}
}
}
正如您所见,关键字“subselect”对所有子级别都是通用的,它的值始终是一个字典,但它的存在是可选的。嵌套的数量可能会改变。 我正在寻找一个允许我执行以下操作的函数:
# desired function that uses recursion I belive.
collect_config(conf, 'trace', 'subselect')
其中 'trace' 是一个 dict 的键,可能有一个 'subselect' dict 作为值。
它应该返回
{'subselect':{
'something': 'jaja',
'roi_spectra': [1, 2],
'roi_x_pixel_spec':
'slice(400, 1200)'
}
或者如果我要求
collect_config(conf, "spec", "subselect")
它应该返回
{'subselect':{
'roi_spectra': [0],
'roi_x_pixel_spec':
'slice(400, 1200)',
'x_property': 'wavenumber'
}
我基本上想要的是一种将键的值从顶层传递到较低层并让较低层覆盖顶层值的方法。 很像类的继承,但使用字典。
所以我需要一个横穿 dict 的函数,找到所需键的路径(此处为“trace”或“spec”并用更高级别的值填充其值(此处为“subselect”),但仅如果更高级别的值不存在。
糟糕的解决方案
我目前有一种如下所示的实现。
# This traverses the dict and gives me the path to get there as a list.
def traverse(dic, path=None):
if not path:
path=[]
if isinstance(dic, dict):
for x in dic.keys():
local_path = path[:]
local_path.append(x)
for b in traverse(dic[x], local_path):
yield b
else:
yield path, dic
# Traverses through config and searches for the property(keyword) prop.
# higher levels will update the return
# once we reached the level of the name (max_depth) only
# the path with name in it is of interes. All other paths are to
# be ignored.
def collect_config(config, name, prop, max_depth):
ret = {}
for x in traverse(config):
path = x[0]
kwg = path[-1]
value = x[1]
current_depth = len(path)
# We only care about the given property.
if prop not in path:
continue
if current_depth < max_depth or (current_depth == max_depth and name in path):
ret.update({kwg: value})
return ret
然后我可以调用它
read_config(conf, "trace", 'subselect', 4)
得到
{'roi_spectra': [0],
'roi_x_pixel_spec': 'slice(400, 1200)',
'something': 'jaja'}
更新
jdehesa 差不多了,但我也可以有一个如下所示的配置:
conf = {
'subselect': {'test': 'jaja'}
'bg0': {
'subselect': {'roi_spectra': [0, 1, 2]}},
'bg1': {
'subselect': {'test': 'nene'}},
}
collect_config(conf, 'bg0', 'subselect')
{'roi_spectra': [0, 1, 2]}
而不是
{'roi_spectra': [0, 1, 2], 'test': 'jaja'}
【问题讨论】:
-
所以基本上你想要由最后一个参数命名的字典(提供详细信息),并使用从第二个参数加上最后一个参数形成的路径加载的覆盖进行更新。
-
函数应该如何找出顶级
conf字典中的键?在您的示例中,只有一个键cc0。如果总是只有一个键,那有什么意义呢?如果有时不止一个,应该取哪一个? -
你能检查一下这是否对你有帮助吗(stackoverflow.com/questions/9807634/…)
-
我已经更新了我的解决方案以解决您添加的情况。
-
愿意回答我的问题吗?如果
conf包含两个字典"cc0"和"cc1",并且它们都包含一个键"spec",那么您希望collect_config(conf, "spec", "subselect")返回哪一个?老实说,我不明白你到底想要什么,以及为什么选择使用这种数据结构。
标签: python dictionary inheritance recursion