How to delete a key from the dictionary using Python function. Sample code I wrote but throwing null dictionary
myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
class my_dict(dict):
def remove_key(self,myD, key):
del myD[key]
dict_obj = my_dict()
dict_obj.remove_key(myDict,'A')
print(dict_obj)
Desired output :
{'B': [('No!', '2')]}
I can use the dictionary comprehension below but not the case.
{k: v for k, v in myDict.items() if 'A' not in k}
Python's function allows you to directly eliminate the key and with it the value it possesses, it turns out to be in my thinking the most optimal way because it is a function proper to language
myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
del myDict['A']
print(myDict)
try:
del myDict["A"]# input your key here
except KeyError:
print("Key 'A' not found")#gives informative feedback if key not in dict
Try this (edited after realizing there is a class method):
# the variable to change
myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
class my_dict(dict):
def remove_key(self,myD, key):
myD.pop(key) # <-- change the parameter passed
# a separate instance of the class (separate from var to change)
dict_obj = my_dict() #<-- this instance has nothing/ empty dictionary
dict_obj.remove_key(myDict,'A')
print(dict_obj) #<-- you will get an empty dictionary here
print(myDict) #<-- myDict has changed
Explanation:
del just delete the local variable. To remove something from a dictionary, use pop method.
Edited: del removes local variable. When you give a dictionary[key], it removes the element from dictionary. When you give a list[index], it removes the element from the list. However, its readability is not good. Therefore, following "explicit is better than implicit", I suggest to use pop. <-- yes, this is an opinion.
The main point here is that OP is confusing between dictionary parameter and inheriting a dictionary as an object. That's why I highlight them in the comments. Peace.
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.