Skip to main content
 首页 » 编程设计

python之如何深入字典并删除最深的键级别

2025年01月19日8zhujiabin

假设我有以下字典对象:

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}} 

这个字典会自动构建,我想要一个函数来将这个字典深入到最深的键级别,并用默认值替换这个键。这里没有给出字典是三层深度,也没有给出以 Third_ 开头的键,字典也可以是 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}} 

因此 Third_level0、Third_level1 和 Third_level2 下的项目被替换为 1

到目前为止我已经尝试过:

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,您可以使用递归来处理任意深度的数据:

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}} 
 
def update_dict(d): 
   return {a:1 if isinstance(a, str) and a.startswith('Third_level') else update_dict(b) if isinstance(b, dict) else b for a, b in d.items()} 
 
print(update_dict(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': 1}, 1.0: 1.0}}, 6: {'Second_level3': {0.0: 6.0, 1.0: 7.0}}, 'Third_level2': 1}}