[英]How to delete a key from the dictionary using Python function
如何使用Python函数从字典中删除键。 我编写的示例代码但是抛出空字典
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)
所需输出:
{'B': [('No!', '2')]}
我可以在下面使用字典理解,但不能使用这种情况。
{k: v for k, v in myDict.items() if 'A' not in k}
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
试试看(意识到存在一个类方法后编辑):
# 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
说明:
del只是删除局部变量。 要从字典中删除某些内容,请使用pop方法。
编辑:del删除局部变量。 当您提供一个dictionary [key]时,它将删除字典中的元素。 提供列表[索引]时,它将从列表中删除元素。 但是,其可读性不好。 因此,遵循“显式优于隐式”,我建议使用pop。 <-是的,这是一种意见。
这里的主要要点是OP混淆了字典参数和继承字典作为对象。 这就是为什么我在评论中突出显示它们。 和平。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.