字典 pop() 方法
pop() 方法用於從字典中刪除具有指定鍵的字典中的項目。
用法:
dictionary_name.pop(key, value)
參數:
key
- 它表示要刪除其值的指定鍵。value
- 可選參數,用於指定字典中不存在“key”時返回的值。
返回值:
該方法的返回類型是值的類型,它返回被移除的值。
注意:如果我們不指定value
和key
字典中不存在,則方法返回錯誤。
範例1:
# Python Dictionary pop() Method with Example
# dictionary declaration
student = {
"roll_no":101,
"name":"Shivang",
"course":"B.Tech",
"perc":98.5
}
# printing dictionary
print("data of student dictionary...")
print(student)
# removing 'roll_no'
x = student.pop('roll_no')
print(x, ' is removed.')
# removing 'name'
x = student.pop('name')
print(x, ' is removed.')
# removing 'course'
x = student.pop('course')
print(x, ' is removed.')
# removing 'perc'
x = student.pop('perc')
print(x, ' is removed.')
# printing default value if key does
# not exist
x = student.pop('address', 'address does not exist.')
print(x)
輸出
data of student dictionary... {'course':'B.Tech', 'roll_no':101, 'perc':98.5, 'name':'Shivang'} 101 is removed. Shivang is removed. B.Tech is removed. 98.5 is removed. address does not exist.
演示示例,如果鍵不存在且未指定值。
範例2:
# Python Dictionary pop() Method with Example
# dictionary declaration
student = {
"roll_no":101,
"name":"Shivang",
"course":"B.Tech",
"perc":98.5
}
# printing dictionary
print("data of student dictionary...")
print(student)
# demonstrating, when method returns an error
# if key does not exist and value is not specified
student.pop('address')
輸出
data of student dictionary... {'course':'B.Tech', 'name':'Shivang', 'roll_no':101, 'perc':98.5} Traceback (most recent call last): File "main.py", line 17, in <module> student.pop('address') KeyError:'address'
相關用法
- Python Dictionary popitem()用法及代碼示例
- Python Dictionary fromkeys()用法及代碼示例
- Python Dictionary clear()用法及代碼示例
- Python Dictionary update()用法及代碼示例
- Python Dictionary setdefault()用法及代碼示例
- Python Dictionary has_key()用法及代碼示例
- Python Dictionary get()用法及代碼示例
- Python Dictionary items()用法及代碼示例
- Python Dictionary copy()用法及代碼示例
- Python Dictionary keys()用法及代碼示例
- Python Dictionary values()用法及代碼示例
- Python Decimal shift()用法及代碼示例
- Python Decimal next_plus()用法及代碼示例
- Python Decimal logical_and()用法及代碼示例
- Python Decimal rotate()用法及代碼示例
- Python Decimal max_mag()用法及代碼示例
- Python Datetime.replace()用法及代碼示例
- Python Decimal as_integer_ratio()用法及代碼示例
- Python DataFrame.to_excel()用法及代碼示例
- Python Pandas DataFrame.fillna()用法及代碼示例
注:本文由純淨天空篩選整理自 Python Dictionary pop() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。