6. Python popitem()

发布时间:2023-12-08

Python popitem()

更新:2022-07-24 12:58 Python 中的 popitem() 函数从字典中移除最后插入的元素对(键、值)。移除的元素作为输出返回。因此,我们可以说这种方法使用后进先出策略。

dict.popitem()

popitem() 参数:

popitem() 方法不接受任何参数。这种方法用在集合算法中,是破坏性地遍历字典的最佳方式。

popitem() 返回值

如果字典为空,popitem() 方法会引发 KeyError。

投入 返回值
字典 最后插入的元素(元组)

Python 中 popitem() 方法的示例

示例 popitem() 在 Python 中是如何工作的?

persondet = {'name': 'Jhon', 'age': 35, 'salary': 5000.0}
# ('salary', 5000.0) is inserted at the last, so it is removed.
output= persondet.popitem()
print('Output Value = ', output)
print('Personal Details = ', persondet)
# inserting a new element pair
persondet['job'] = 'Electritian'
# now ('job', 'Electritian') is the latest element
output = persondet.popitem()
print('Output Value = ', output)
print('Personal Details = ', persondet)

输出:

Output Value =  ('salary', 5000.0)
Personal Details =  {'name': 'Jhon', 'age': 35}
Output Value =  ('job', 'Electritian')
Personal Details =  {'name': 'Jhon', 'age': 35}

示例 2: popitem() 用空字典引发 KeyError

persondet = {}  
# Displaying result  
print(persondet)  
per = persondet.popitem()  
print("Removed",per)  
print(persondet)

输出:

KeyError: 'popitem(): dictionary is empty'