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

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


当前回答

del陈述就是你要找的。如果您有一个名为foo的字典,其键名为“bar”,则可以像这样从foo中删除“bar”:

del foo['bar']

请注意,这将永久修改正在操作的词典。如果您想保留原始词典,则必须事先创建一个副本:

>>> foo = {'bar': 'baz'}
>>> fu = dict(foo)
>>> del foo['bar']
>>> print foo
{}
>>> print fu
{'bar': 'baz'}

dict调用生成一个浅显的副本。如果需要深度复制,请使用copy.depcopy。

为了方便,您可以复制并粘贴以下方法:

def minus_key(key, dictionary):
    shallow_copy = dict(dictionary)
    del shallow_copy[key]
    return shallow_copy

其他回答

我认为你的解决方案是最好的方法。但如果你想要另一个解决方案,你可以使用旧字典中的关键字创建一个新字典,而不包括你指定的关键字,如下所示:

>>> a
{0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> {i:a[i] for i in a if i!=0}
{1: 'one', 2: 'two', 3: 'three'}

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

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

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

这里是顶级设计方法:

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}

希望这有帮助!

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

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}

del陈述就是你要找的。如果您有一个名为foo的字典,其键名为“bar”,则可以像这样从foo中删除“bar”:

del foo['bar']

请注意,这将永久修改正在操作的词典。如果您想保留原始词典,则必须事先创建一个副本:

>>> foo = {'bar': 'baz'}
>>> fu = dict(foo)
>>> del foo['bar']
>>> print foo
{}
>>> print fu
{'bar': 'baz'}

dict调用生成一个浅显的副本。如果需要深度复制,请使用copy.depcopy。

为了方便,您可以复制并粘贴以下方法:

def minus_key(key, dictionary):
    shallow_copy = dict(dictionary)
    del shallow_copy[key]
    return shallow_copy