简体   繁体   English

如何使用Python函数从字典中删除特定键

[英]How to remove particular key from the dictionary with Python function

I have a dictionary and trying to remove key from the dictionary 我有一本字典,试图从字典中删除密钥

class my_dict(dict): 

    # __init__ function 
    def __init__(self): 
        self = dict() 

    # Function to add key:value 
    def add(self, key, value): 
        self[key] = value
    # Function to remove key:value 
    def removekey(key):
        del key
dict_obj = my_dict() 
dict_obj.add(1, 'one') 
dict_obj.add(2, 'two') 

print(dict_obj) 

>> {1: 'one', 2: 'two'}

Once I do 一旦我做

dict_obj.removekey(1) 

TypeError: removekey() takes 1 positional argument but 2 were given TypeError:removekey()接受1个位置参数,但给出了2个

class my_dict(dict): 

    # __init__ function 
    def __init__(self): 
        self = dict() 

    # Function to add key:value 
    def add(self, key, value): 
        self[key] = value
    # Function to remove key:value 
    def removekey(self,key):
        del self[key]
dict_obj = my_dict() 
dict_obj.add(1, 'one') 
dict_obj.add(1, 'three') 

dict_obj.add(2, 'two') 
print(dict_obj) 

dict_obj.removekey(1) 
print(dict_obj) 

You're doing nothing in the delete function. 您在删除功能中什么也没做。 Doing del key just deletes the parameter you just passed and does nothing on the dict. 进行del key只会删除您刚刚传递的参数,而对字典没有任何作用。

Edit your code this way. 用这种方式编辑代码。

# Function to remove key:value 
def removekey(self, key):
    return self.pop(key, None)

It will also return the deleted item or None if it does not exists. 它还将返回已删除的项目,如果不存在则返回None。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM