我有一个嵌套字典,即
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
答案 0 :(得分:3)
我会reduce
在dict.get
上除了找到最内层词典的最后一个键之外的所有词,然后使用最终键在del
上调用dict
。< / p>
def f(dictionary,key_list):
dictionary = reduce(dict.get, key_list[0:-1], dictionary)
del dictionary[key_list[-1]]
a={'k1':{'k2':1}}
print(a)
f(a,['k1','k2'])
print(a)
结果:
$ python x.py
{'k1': {'k2': 1}}
{'k1': {}}
答案 1 :(得分:2)
您只想从最里面的字典中删除,而不是从外部字典中删除。因此,要获取到最里面的字典的路径,您需要使用getitem
,而不是delitem
。只应使用最后一个密钥进行删除:
def f(dictionary, key_list):
*path, key = key_list
del reduce(operator.getitem, path, dictionary)[key]
演示(还有一个更清晰的级别):
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)