📅  最后修改于: 2020-09-20 04:45:43             🧑  作者: Mango
pop()
方法的语法是
dictionary.pop(key[, default])
pop()
方法采用两个参数:
pop()
方法返回:
key
-从字典中删除/弹出元素key
-将值指定为第二个参数(默认值) key
是没有找到和默认参数不指定- KeyError
引发异常# 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}
# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
element = sales.pop('guava')
输出
KeyError: 'guava'
# 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}