如何从任意嵌套的字典中删除

2024-09-28 15:28:35 发布

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

我有一个使用NestedDict类的代码:How can I access a deeply nested dictionary using tuples?。“根据@JCash的回答,我有一个完全可行的例子:“

有两件事我想用它来做,这给我带来了麻烦。首先,我想删除其中一个元素,如果该元素的值为零。第二,如果一个元素是一个空字典,因为该字典的所有条目都被删除了,我想删除这个空字典。在

使用上面的类,示例如下:

my_tuple = (0, 1, 0, 0, 0, 1, 0, 0)
d = NestedDict()
print d
d[my_tuple] = 4
print d

#del d[my_tuple]

del d[0][1][0][0][0][1][0][0]
del d[0][1][0][0][0][1][0]
del d[0][1][0][0][0][1]
del d[0][1][0][0][0]
del d[0][1][0][0]
del d[0][1][0]
del d[0][1]
del d[0]

print d

为了摆脱多层嵌套,del的长列表是必要的。注释掉的del语句(它给出一个键错误)是我想要实现的,具有任意长度的元组。在

删除中间层应该不难,一旦我知道如何删除第一个。我已经知道要删除的内容,可以使用以下命令测试空字典:if(dictionary entry)={})

有什么想法吗?在

编辑:输出为:

^{pr2}$

Tags: 代码元素dictionary字典accessmycanhow
1条回答
网友
1楼 · 发布于 2024-09-28 15:28:35

生成了一个函数deepdelete,该函数接受一个键列表并递归地删除叶,然后是任何现在为空的分支字典:

def deepdelete(branch, keys):
    if len(keys) > 1:                                  # not at the leaf
        empty = deepdelete(branch[keys[0]], keys[1:])  # recursion
        if empty:                                      
            del branch[keys[0]]                        # delete branch
    else:                                              # at the leaf
        del branch[keys[0]]                            # delete the leaf
    return len(branch) == 0                            # could return len

deepdelete(d, delkeys)

把你举的字典作为例子:

^{pr2}$

输出:

{}

把更有趣的字典和其他分支一起传来:

d = {0: {1: {0: {0: {0: {1: {0: {0: 4}}, 'no_delete': 2}, 'other_data': 3}, 'keep_me': 4}, 'special': 4}, 'preserve': 1}, 'important': 50}
deepdelete(d, (0, 1, 0, 0, 0, 1, 0, 0))

输出:

{0: {'preserve': 1, 1: {0: {0: {0: {'no_delete': 2}, 'other_data': 3}, 'keep_me': 4}, 'special': 4}}, 'important': 50}

相关问题 更多 >