【发布时间】:2020-05-17 07:06:49
【问题描述】:
我有一个深度嵌套的字典(任意键和值),例如:
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)
并让结果字典看起来像:
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'
}
}
}
.
.
.
}
我知道我可以像这样使用递归循环遍历字典:
def prepend(directory, config):
for k, v in config.items():
if isinstance(v, dict):
prepend(directory, v)
else:
# do something
但是,我无法在迭代期间更改值。非常感谢任何和所有帮助!谢谢!
【问题讨论】:
-
else: # do something中有什么?你如何尝试改变价值?您是否尝试更改config[k]而不是v的值?
标签: python python-3.x dictionary prepend