【问题标题】:How to delete a key from the dictionary using Python function如何使用 Python 函数从字典中删除一个键
【发布时间】:2019-08-06 02:58:29
【问题描述】:

如何使用 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}

【问题讨论】:

  • 不能直接使用dict.pop(key)或者直接拨打del dict[key]吗?
  • 请用文字更详细地解释您要做什么。您的remove_key 是一种方法,它接受两个字典:selfmyD。您希望他们每个人发生什么,您希望返回什么?现在,您正在删除 myD 中的键,然后返回 self(它曾经是并且仍然是一个空字典)。

标签: python function class dictionary


【解决方案1】:

Python 的函数可以让你直接删除键和它所拥有的值,事实证明这是我认为最优化的方式,因为它是一个适合语言的函数

    myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
    del myDict['A']
    print(myDict)

【讨论】:

  • 能否将结果添加到代码块而不是图像中?
  • 当然,朋友,非常感谢您的建议
【解决方案2】:
try:
    del myDict["A"]# input your key here
except KeyError:
    print("Key 'A' not found")#gives informative feedback if key not in dict

【讨论】:

    【解决方案3】:

    试试这个(意识到有类方法后编辑):

    # 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 删除局部变量。当您提供字典[key] 时,它会从字典中删除元素。当你给出一个 list[index] 时,它会从列表中删除元素。但是,它的可读性并不好。因此,遵循“显式优于隐式”,我建议使用pop。

    这里的要点是 OP 混淆了字典参数和继承字典作为对象。这就是我在 cmets 中突出显示它们的原因。和平。

    【讨论】:

    • 为什么我们需要明确地给出 dict_obj = dict_obj.remove_key(myDict,'A')
    • del 对于普通名称仅删除变量绑定。但是del myD[key]会从字典中删除键(及其关联的值),比调用pop效率更高;如果您需要删除键/值对返回值(或者如果您传递第二个参数,则仅在键不存在时删除绑定而不引发异常时才调用pop )。这不会以任何方式修复 OP 的代码;更改后的代码在功能上是等效的,只是效率稍低。
    猜你喜欢
    • 2022-08-08
    • 2012-07-01
    • 2021-11-18
    • 1970-01-01
    • 2023-01-09
    • 2016-07-07
    • 1970-01-01
    相关资源
    最近更新 更多