[英]How to delete a key from the dictionary using Python function
How to delete a key from the dictionary using Python function. 如何使用Python函数从字典中删除键。 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 Python的功能允许您直接消除键并拥有它所拥有的价值,这在我看来是最理想的方式,因为它是适合语言的功能
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. del只是删除局部变量。 To remove something from a dictionary, use pop method. 要从字典中删除某些内容,请使用pop方法。
Edited: del removes local variable. 编辑:del删除局部变量。 When you give a dictionary[key], it removes the element from dictionary. 当您提供一个dictionary [key]时,它将删除字典中的元素。 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. 因此,遵循“显式优于隐式”,我建议使用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. 这里的主要要点是OP混淆了字典参数和继承字典作为对象。 That's why I highlight them in the comments. 这就是为什么我在评论中突出显示它们。 Peace. 和平。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.