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'
總結
以上是生活随笔為你收集整理的python中pop用法_Python dict pop()用法及代码示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: redis如何设置定时过期_redis补
- 下一篇: 字符串处理 - DataFrame文本数