python中pop用法_Python dict pop()用法及代码示例
Python语言为几乎所有容器(无论是列表容器还是集合容器)指定了pop()。这篇特别的文章着重说明Python词典提供的pop()方法。这种方法对于经常处理字典的程序员很有用。用法:dict.pop(key, def)参数:key:必须返回并删除其键值对的键。def:如果指定的键不存在,则返回的默认值。返回:如果存在键,则与已删除键/值对关联的值。如果不存在 key ,则指定为默认值。KeyEr
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)