如何在Python中从字典中删除项目?

在不修改原始词典的情况下,如何获取删除了该项的另一个词典?


当前回答

只需调用del d[“key”]。

然而,在生产中,检查d中是否存在“key”始终是一个好的做法。

if 'key' in d:
    del d['key']

其他回答

使用del可以删除传递该值键的dict值

链接:德尔法

del dictionary['key_to_del']

pop改变了字典。

 >>> lol = {"hello": "gdbye"}
 >>> lol.pop("hello")
     'gdbye'
 >>> lol
     {}

如果你想保留原件,你可以复制它。

下面的代码片段肯定会帮助您,我在每行中都添加了注释,这将帮助您理解代码。

def execute():
   dic = {'a':1,'b':2}
   dic2 = remove_key_from_dict(dic, 'b')  
   print(dict2)           # {'a': 1}
   print(dict)            # {'a':1,'b':2}

def remove_key_from_dict(dictionary_to_use, key_to_delete):
   copy_of_dict = dict(dictionary_to_use)     # creating clone/copy of the dictionary
   if key_to_delete in copy_of_dict :         # checking given key is present in the dictionary
       del copy_of_dict [key_to_delete]       # deleting the key from the dictionary 
   return copy_of_dict                        # returning the final dictionary

或者也可以使用dict.pop()

d = {"a": 1, "b": 2}

res = d.pop("c")  # No `KeyError` here
print (res)       # this line will not execute

或者更好的方法是

res = d.pop("c", "key not found")
print (res)   # key not found
print (d)     # {"a": 1, "b": 2}

res = d.pop("b", "key not found")
print (res)   # 2
print (d)     # {"a": 1}

…我如何从字典中删除项目以返回副本(即不修改原件)?

dict是用于此目的的错误数据结构。

当然,复制字典并从副本中弹出是有效的,建立一个新的字典并理解它也是有效的,但是所有的复制都需要时间,你已经用线性时间操作代替了恒定时间操作。并且所有这些活动副本一次占用每个副本的空间线性空间。

其他数据结构,如哈希数组映射尝试,正是为这种用例而设计的:添加或删除元素会在对数时间内返回副本,并与原始元素共享大部分存储空间。1

当然,也有一些缺点。性能是对数而不是常数(尽管基数较大,通常为32-128)。而且,虽然可以使非变异API与dict相同,但“变异”API明显不同。最重要的是,Python中没有HAMT电池。2

pyristent库是Python的基于HAMT的dict替换(以及各种其他类型)的一个非常可靠的实现。它甚至有一个漂亮的evolver API,用于将现有的变异代码尽可能平滑地移植到持久代码。但如果你想明确地返回拷贝而不是变异,你可以这样使用:

>>> from pyrsistent import m
>>> d1 = m(a=1, b=2)
>>> d2 = d1.set('c', 3)
>>> d3 = d1.remove('a')
>>> d1
pmap({'a': 1, 'b': 2})
>>> d2
pmap({'c': 3, 'a': 1, 'b': 2})
>>> d3
pmap({'b': 2})

d3=d1.remove('a')正是问题所要求的。

如果您在pmap中嵌入了dict和list等可变数据结构,那么仍然会存在别名问题,您只能通过一直保持不变,嵌入pmap和pvectors来解决这个问题。


1.HAMT在Scala、Clojure、Haskell等语言中也很流行,因为它们在无锁编程和软件事务内存方面表现得很好,但这两者在Python中都不太相关。

2.事实上,stdlib中有一个HAMT,用于contextvars的实现。先前撤回的政治公众人物解释了原因。但这是库的隐藏实现细节,而不是公共集合类型。

这里是顶级设计方法:

def eraseElement(d,k):
    if isinstance(d, dict):
        if k in d:
            d.pop(k)
            print(d)
        else:
            print("Cannot find matching key")
    else:
        print("Not able to delete")


exp = {'A':34, 'B':55, 'C':87}
eraseElement(exp, 'C')

我将字典和我想要的键传递到我的函数中,验证它是否是字典,以及键是否正常,如果两者都存在,则从字典中删除值并打印出剩余的值。

输出:{“B”:55,“A”:34}

希望这有帮助!