Python 字典 pop 函数

Python 字典的 pop 函数用于移除指定键位置的项并打印被移除的值。字典 pop 函数的语法如下所示。

dictionary_name.pop(key, default_value)

Python 字典 pop 示例

pop 函数通过指定键移除键值对并打印该值。

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}
print("Dictionary Items: ", myDict)

print("\nRemoved Item      :  ",  myDict.pop(3))
print("Dictionary Items  :  ",  myDict)

print("\nRemoved Item      :  ",  myDict.pop(1))
print("Dictionary Items  :  ",  myDict)
Dictionary pop Function Example

在此程序中,我们尝试 pop 或移除一个不存在的 字典 项。如您所见,Python 抛出了一个错误。

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}
print("Dictionary Items: ", myDict)

# Pop Non-existing Values
print("\nRemoved Item      :  ",  myDict.pop(5))
print("Dictionary Items  :  ",  myDict)
Dictionary Items:  {1: 'apple', 2: 'Banana', 3: 'Orange', 4: 'Kiwi'}
Traceback (most recent call last):
  File "/Users/suresh/Desktop/simple.py", line 5, in <module>
    print("\nRemoved Item      :  ",  myDict.pop(5))
KeyError: 5
>>> 

在此字典 pop 程序中,我们使用第二个参数来显示默认值。当您尝试从字典中移除不存在的项时,下面的代码将返回“对不起!没有此项”的消息。

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}
print("Dictionary Items: ", myDict)

# Non-existing Values
print("\nRemoved Item      :  ",  myDict.pop(5, 'Sorry!! No Item exists'))
Dictionary Items:  {1: 'apple', 2: 'Banana', 3: 'Orange', 4: 'Kiwi'}

Removed Item      :   Sorry!! No Item exists