我有一个深度嵌套的字典(任意键和值),如:
data = {
'a': {
'path': '/a/a.txt'
},
'b': {
'b1': {
'path': '/b/b1/b1.txt'
},
'b2': {
'path': '/b/b2/b2.txt'
}
}
'c': {
'c1': {
'c12': {
'path': '/c/c1/c12/c12.txt'
}
},
'c2': {
'c22': {
'path': '/c/c1/c22/c22.txt'
}
},
'c3': {
'c32': {
'path': '/c/c1/c32/c32.txt'
}
}
}
.
.
.
}
我的目标是在字典中的每个值前面加上一个特定的路径。因此,基本上,接受上述数据,对其进行操作:
def prepend(value, data):
return magic
data = prepend('predir/z', data)
并使生成的dict看起来像:
data = {
'a': {
'path': 'predir/z/a/a.txt'
},
'b': {
'b1': {
'path': 'predir/z/b/b1/b1.txt'
},
'b2': {
'path': 'predir/z/b/b2/b2.txt'
}
}
'c': {
'c1': {
'c12': {
'path': 'predir/z/c/c1/c12/c12.txt'
}
},
'c2': {
'c22': {
'path': 'predir/z/c/c1/c22/c22.txt'
}
},
'c3': {
'c32': {
'path': 'predir/z/c/c1/c32/c32.txt'
}
}
}
.
.
.
}
我知道我可以使用递归在dict中循环,如下所示:
def prepend(directory, config):
for k, v in config.items():
if isinstance(v, dict):
prepend(directory, v)
else:
# do something
但是,我无法在迭代期间更改值。非常感谢您的任何帮助!谢谢大家!
在
else
分支中,只需将前缀添加到现有值,并将其存储在键中:你必须使用
或
它将直接更改原始
data
中的值,所以您不需要return config
顺便说一句:如果要保留原始数据,则必须在函数中创建
new_config
相关问题 更多 >
编程相关推荐