简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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