Python 字典 pop() 方法

pop() 方法从字典中移除并返回具有给定键的元素。

示例

# create a dictionary
marks = { 'Physics': 67, 'Chemistry': 72, 'Math': 89 }

element = marks.pop('Chemistry')
print('Popped Marks:', element) # Output: Popped Marks: 72

字典 pop() 的语法

pop() 方法的语法是

dictionary.pop(key[, default])

pop() 参数

pop() 方法接受两个参数

  • key - 要搜索并移除的键
  • default - 当键不在字典中时要返回的值

pop() 的返回值

pop() 方法返回

  • 如果找到 key - 从字典中移除/弹出的元素
  • 如果未找到 key - 作为第二个参数(default)指定的值
  • 如果未找到 key 且未指定默认参数 - 抛出 KeyError 异常

示例 1:从字典中弹出一个元素

# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

element = sales.pop('apple')
print('The popped element is:', element) print('The dictionary is:', sales)

输出

The popped element is: 2
The dictionary is: {'orange': 3, 'grapes': 4}

示例 2:从字典中弹出一个不存在的元素

# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

element = sales.pop('guava')

输出

KeyError: 'guava'

示例 3:从字典中弹出一个不存在的元素,并提供默认值

# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

element = sales.pop('guava', 'banana')
print('The popped element is:', element) print('The dictionary is:', sales)

输出

The popped element is: banana
The dictionary is: {'orange': 3, 'apple': 2, 'grapes': 4}

另请阅读

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

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

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

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