gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:37:26 25 4
gpt4 key购买 nike

我有一个嵌套字典,即

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)

关于python - 通过键列表从嵌套的 python 字典中删除键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47911607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com