我正在使用这个SSM方法从我的AWS参数存储中获取一组敏感凭据。path语法允许我同时提取一堆相关的凭据,这很酷,但正如您所看到的,返回格式更像是一个dicts列表。我去掉了一些东西,以便能够以这样的格式获取我的所有参数:
{
'/a/b/c/d/e': 'xxxxxxxx',
'/a/b/c/d/f': 'xxxxxx',
'/a/b/c/g': 'xxxxxx'
}但是,我很难将这种格式传递到某种(im假设为递归的)函数中,该函数可以将带有路径键的裁剪重新格式化为实际嵌套的dict,如下所示:
{
'a': {
'b': {
'c': {
'd': {
'e': 'xxxxxxx',
'f': 'xxxxxxx'
},
'g': 'xxxxxxx'
}
}
}
}以前有人做过这样的事吗?
发布于 2019-03-12 14:46:04
试试这个:
d = {
'/a/b/c/d/e': 'xxxxxxxx',
'/a/b/c/d/f': 'xxxxxx',
'/a/b/c/g': 'xxxxxx'
}
output = {}
for key, value in d.items():
directories = key.split('/')[1:]
helper = output
for dire in directories[:-1]:
if dire not in helper:
helper[dire] = {}
helper = helper[dire]
helper[directories[-1]] = value
print(output)产出如下:
{
'a': {
'b': {
'c': {
'd': {
'e': 'xxxxxxxx',
'f': 'xxxxxx'
},
'g': 'xxxxxx'
}
}
}
}发布于 2019-03-12 15:35:57
你可以像翻阅一样继承字典。
class RecursiveDict(dict):
def __missing__(self, key):
self.__setleaf__(key, RecursiveDict())
return self[key]
def __setleaf__(self,key,value):
super(RecursiveDict, self).__setitem__(key,value)
def __setitem__(self, key,value):
keys = key.strip('/').split('/')
tmp = self
for k in keys[:-1]:
tmp = tmp[k]
tmp.__setleaf__(keys[-1],value)您可以按以下方式使用它
d = RecursiveDict()
d['/a/b/c/d/e'] = 'xxxxxxxx'
d['/a/b/c/d/f'] = 'xxxxxx'
print(d)发布于 2019-03-12 14:54:24
这种方法并不能很好地配合您所寻找的内容,但是如果分隔符是一个句点而不是正斜杠,它将完美地工作。
输入:
{
'a.b.c.d.e': 'xxxxxxxx',
'a.b.c.d.f': 'xxxxxx',
'a.b.c.g': 'xxxxxx'
}输出:
{'a': {'b': {'c': {'g': 'xxxxxx', 'd': {'f': 'xxxxxx', 'e': 'xxxxxxxx'}}}}}https://stackoverflow.com/questions/55123926
复制相似问题