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) is inserted at the last, so it is removed.
result = person.popitem()

print('Return Value = ', result)
print('person = ', person)

# inserting a new element pair
person['profession'] = 'Plumber'

# now ('profession', 'Plumber') is the latest element
result = person.popitem()

print('Return Value = ', result)
print('person = ', person)

输出

Return Value =  ('salary', 3500.0)
person =  {'name': 'Phill', 'age': 22}
Return Value =  ('profession', 'Plumber')
person =  {'name': 'Phill', 'age': 22}

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


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战