跳到主要内容

Python 字典 popitem() 方法

popitem() 的语法是:

dict.popitem()

popitem() 方法的参数

popitem() 方法不接受任何参数。

popitem() 方法的返回值

popitem() 方法以 后进先出(LIFO)的顺序从字典中移除并返回一个(键, 值)对。

  • 返回字典中最后插入的元素 (键, 值) 对。
  • 从字典中移除返回的元素对。

注意: 在 Python 3.7 之前,popitem() 方法从字典中返回并移除了一个任意的元素(键, 值)对。

示例:popitem() 方法的工作原理

person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}

# ('salary', 3500.0) 是最后插入的,因此它被移除。
result = person.popitem()

print('返回值 = ', result)
print('person = ', person)

# 插入一个新的元素对
person['profession'] = 'Plumber'

# 现在 ('profession', 'Plumber') 是最新的元素
result = person.popitem()

print('返回值 = ', result)
print('person = ', person)

输出

返回值 = ('salary', 3500.0)
person = {'name': 'Phill', 'age': 22}
返回值 = ('profession', 'Plumber')
person = {'name': 'Phill', 'age': 22}

注意:如果字典为空,popitem() 方法会引发 KeyError 错误。