[英]How to remove particular key from the dictionary with Python function
我有一本字典,試圖從字典中刪除密鑰
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'}
一旦我做
dict_obj.removekey(1)
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)
您在刪除功能中什么也沒做。 進行del key
只會刪除您剛剛傳遞的參數,而對字典沒有任何作用。
用這種方式編輯代碼。
# Function to remove key:value
def removekey(self, key):
return self.pop(key, None)
它還將返回已刪除的項目,如果不存在則返回None。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.