Python 字典 pop() 方法

Python 字典

描述

Python 字典 pop() 方法删除字典给定键 key 所对应的值,返回值为被删除的值。

语法

pop() 方法语法:

pop(key[,default])

参数

key - 要删除的键

default - 当键 key 不存在时返回的值

返回值

返回被删除的值:

如果 key 存在 - 删除字典中对应的元素

如果 key 不存在 - 返回设置指定的默认值 default

如果 key 不存在且默认值 default 没有指定 - 触发 KeyError 异常

实例

以下实例展示了 pop() 方法的使用方法:

实例

#!/usr/bin/python

# -*- coding: UTF-8 -*-

site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}

element = site.pop('name')

print('删除的元素为:')

print(element)

print('字典为:')

print(site)

输出结果为:

删除的元素为:

菜鸟教程

字典为:

{'url': 'www.runoob.com', 'alexa': 10000}

如果删除的键不存在会触发异常:

实例

#!/usr/bin/python

# -*- coding: UTF-8 -*-

site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}

element = site.pop('nickname')

print('删除的元素为:')

print(element)

print('字典为:')

print(site)

输出结果为:

Traceback (most recent call last):

File "test.py", line 6, in

element = site.pop('nickname')

KeyError: 'nickname'

可以设置默认值来避免异常:

实例

#!/usr/bin/python

# -*- coding: UTF-8 -*-

site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}

element = site.pop('nickname', '不存在的 key')

print('删除的元素为:')

print(element)

print('字典为:')

print(site)

输出结果为:

删除的元素为:

不存在的 key

字典为:

{'url': 'www.runoob.com', 'alexa': 10000, 'name': '\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'}

Python 字典