我有一个深层嵌套的字典(任意键和值),例如:
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
分支中,只需将前缀添加到现有值,并将其存储在键中:
def prepend(directory, config):
for k, v in config.items():
if isinstance(v, dict):
prepend(directory, v)
else:
config[k] = directory + v
return config
您必须使用
else:
config[k] = directory + config[k]
或
else:
config[k] = directory + v
并且它将直接更改原始data
中的值,因此您不需要return config
。
BTW:如果要保留原始数据,则必须在函数中创建new_config
。
def prepend(directory, config):
new_config = {}
for k, v in config.items():
if isinstance(v, dict):
new_config[k] = prepend(directory, v)
else:
new_config[k] = directory + v
return new_config
new_data = prepend('predir/z', data)
print(data)
print(new_data)