假设我有以下dictionary对象:
dictionary = {'First_level': {0: {'Second_level0': {0.0: {'Third_level0': {0.0: 7.0, 1.0: 3.0}}}},
2: {'Second_level1': {0.0: 2.0, 1.0: 1.0}},
4: {'Second_level2': {0.0: {'Third_level1': {0.0: 7.0, 1.0: 5.0}}, 1.0: 1.0}},
6: {'Second_level3': {0.0: 6.0, 1.0: 7.0}},
'Third_level2': 7.0}}
这个字典会自动生成,我需要一个函数,可以将这个字典深入到最深的键级别,并用默认值替换这个键。这里没有给出字典是三级深的,也没有给出以第三级开始的键字典也可以是40级深的,其中最深的键是8:0或“A”:1
最后一本词典应该看起来很好。比如:
dictionary = {'First_level': {0: {'Second_level0': {0.0: {'Third_level0': 1}}},
2: {'Second_level1': {0.0: 2.0, 1.0: 1.0}},
4: {'Second_level2': {0.0: {'Third_level1': {0.0: 7.0, 1.0: 5.0}}, 1.0: 1.0}},
6: {'Second_level3': {0.0: 6.0, 1.0: 7.0}},
'Third_level2': 1}}
因此第三级0、第三级1和第三级2下的项目被a1
到目前为止,我已经尝试了:
def delve_dictionary(dictionary=dictionary,default = 1):
for key in dictionary:
item = dictionary[key]
if isinstance(item,dict):
level = delve_dictionary(item)
else:
key = default
return dictionary
delve_dictionary(dictionary=dictionary,default=1)
但显然这不管用。。。你知道吗
{'First_level': {0: {'Second_level0': {0.0: {'Third_level0': {0.0: 7.0,
1.0: 3.0}}}},
2: {'Second_level1': {0.0: 2.0, 1.0: 1.0}},
4: {'Second_level2': {0.0: {'Third_level1': {0.0: 7.0, 1.0: 5.0}},
1.0: 1.0}},
6: {'Second_level3': {0.0: 6.0, 1.0: 7.0}},
'Third_level2': 7.0}}
通过以下方法解决了问题:
假设
Third_level
键的每个最终值都应设置为1
,则可以使用递归来处理任意深度的数据:输出:
相关问题 更多 >
编程相关推荐