如何钻研字典并删除最深的键

2024-09-29 02:18:42 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下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}}

Tags: 对象keydefaultdictionary字典itemlevelfirst
2条回答

通过以下方法解决了问题:

def delve_dictionary(dictionary = dictionary,default = 1):
    for item in dictionary:
        try:
            if isinstance(dictionary[item],dict):
                level = delve(dictionary[item])
            else: 
                dictionary[item] = default
        except:
            ''
    return(dictionary)

delve_dictionary(dictionary=dictionary,default=1)


{'First_level': {0: {'Second_level0': {0.0: {'Third_level0': {0.0: 1,
      1.0: 1}}}},
  2: {'Second_level1': {0.0: 1, 1.0: 1}},
  4: {'Second_level2': {0.0: {'Third_level1': {0.0: 1, 1.0: 1}}, 1.0: 1}},
  6: {'Second_level3': {0.0: 1, 1.0: 1}},
  'Third_level2': 1}}

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

相关问题 更多 >