python中pop用法_Python dict pop()用法及代码示例

Python语言为几乎所有容器(无论是列表容器还是集合容器)指定了pop()。这篇特别的文章着重说明Python词典提供的pop()方法。这种方法对于经常处理字典的程序员很有用。

用法:dict.pop(key, def)

参数:

key:必须返回并删除其键值对的键。

def:如果指定的键不存在,则返回的默认值。

返回:

如果存在键,则与已删除键/值对关联的值。

如果不存在 key ,则指定为默认值。

KeyError,如果不存在 key 且未指定默认值。

代码1:演示工作pop(),当存在 key 时。

# Python 3 code to demonstrate

# working of pop()

# initializing dictionary

test_dict = { "Nikhil" :7, "Akshat" :1, "Akash" :2 }

# Printing initial dict

print ("The dictionary before deletion:" + str(test_dict))

# using pop to return and remove key-value pair.

pop_ele = test_dict.pop('Akash')

# Printing the value associated to popped key

print ("Value associated to poppped key is:" + str(pop_ele))

# Printing dictionary after deletion

print ("Dictionary after deletion is:" + str(test_dict))

输出:

The dictionary before deletion:{'Nikhil':7, 'Akshat':1, 'Akash':2}

Value associated to poppped key is:2

Dictionary after deletion is:{'Nikhil':7, 'Akshat':1}

的行为pop()当字典中不存在该键时,功能会有所不同。在这种情况下,如果没有提供默认值,它将返回提供的默认值或KeyError。

代码2:演示pop()在没有 key 的情况下的工作

# Python 3 code to demonstrate

# working of pop() without key

# initializing dictionary

test_dict = { "Nikhil" :7, "Akshat" :1, "Akash" :2 }

# Printing initial dict

print ("The dictionary before deletion:" + str(test_dict))

# using pop to return and remove key-value pair

# provided default

pop_ele = test_dict.pop('Manjeet', 4)

# Printing the value associated to popped key

# Prints 4

print ("Value associated to poppped key is:" + str(pop_ele))

# using pop to return and remove key-value pair

# not provided default

pop_ele = test_dict.pop('Manjeet')

# Printing the value associated to popped key

# KeyError

print ("Value associated to poppped key is:" + str(pop_ele))

输出:

The dictionary before deletion:{'Nikhil':7, 'Akshat':1, 'Akash':2}

Value associated to poppped key is:4

Traceback (most recent call last):

File "main.py", line 20, in

pop_ele = test_dict.pop('Manjeet')

KeyError:'Manjeet'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值