Skip to main content
 首页 » 编程设计

python之通过键列表从嵌套的 python 字典中删除键

2025年05月04日21zfyouxi

我有一个嵌套字典,即

a={'k1':{'k2':1}} 

我想写一个函数

def f(dictionary,key_list): 
      pass 

f(a,['k1','k2']) 等价于 del(a['k1']['k2'])

我试过

from functools import reduce 
import operator 
 
def f(dictionary,key_list): 
     reduce(operator.delitem,key_list,dictionary) 

不过

f(a,['k1','k2']) 

返回

TypeError: 'NoneType' object does not support item deletion 

请您参考如下方法:

你只想从最里面的字典中删除,而不是从外面的字典中删除。因此,对于到达最内层字典的路径,您需要使用 getitem,而不是 delitem。只应使用最后一个 key 进行删除:

def f(dictionary, key_list): 
    *path, key = key_list 
    del reduce(operator.getitem, path, dictionary)[key] 

Demo(多一层更清晰):

from functools import reduce 
import operator 
 
def f(dictionary, key_list): 
    *path, key = key_list 
    del reduce(operator.getitem, path, dictionary)[key] 
 
a = {'k1': {'k2': {'k3': 1}}} 
f(a, ['k1', 'k2', 'k3']) 
print(a) 

打印 {'k1': {'k2': {}}},与 del a['k1']['k2']['k3'] 之后相同:

a = {'k1': {'k2': {'k3': 1}}} 
del a['k1']['k2']['k3'] 
print(a)