Tutorial Study Image

Python popitem()

Python 中的 popitem() 函数从字典中移除最后插入的元素对(键,值)。并且移除的元素将作为输出返回。因此,我们可以说此方法使用后进先出 (LIFO) 策略。


dict.popitem()
 

popitem() 参数

popitem() 方法不带任何参数。此方法用于集合算法,是破坏性迭代字典的最佳方式。

 

popitem() 返回值

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

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

Python 中 popitem() 方法的示例

示例 1: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'