如何從 Python 字典中刪除鍵?
在 Python 中,字典是一種無序的資料集合,用於儲存資料值,類似於對映,不像其他只儲存單個值的資料型別。字典的鍵必須唯一且為不可變資料型別,例如字串、整數和元組,但鍵值可以重複且可以為任何型別。字典是可變的,因此即使在 Python 中定義字典後,也可以新增或刪除鍵。
有很多方法可以從字典中刪除鍵,以下是一些方法。
使用 pop(key,d)
pop(key, d) 方法從字典中返回鍵的值。它接受兩個引數:要刪除的鍵和一個可選值,如果找不到鍵則返回該值。
示例 1
以下是使用必需鍵引數彈出元素的示例。
#creating a dictionary with key value pairs #Using the pop function to remove a key dict = {1: "a", 2: "b"} print(dict) dict.pop(1) #printing the dictionary after removing a key
輸出
執行上述程式後會生成以下輸出。
{1: 'a', 2: 'b'}
示例 2
在以下示例中,彈出的鍵值透過將彈出的值賦給變數來訪問。
#creating a dictionary with key value pairs #Using the pop function to remove a key dict = {1: "a", 2: "b"} print(dict) value=dict.pop(1) #printing the dictionary after removing a key print(dict) #printing the popped value print(value)
輸出
執行上述程式後會生成以下輸出。
{1: 'a', 2: 'b'}
{2: 'b'}
a
示例 3
以下示例演示了使用del() 函式從字典中刪除鍵。與使用字典的pop() 不同,我們不能使用 del() 函式返回任何值。
#creating a dictionary with key value pairs #Using the pop function to remove a key dict = {1: "a", 2: "b"} print(dict) del(dict[1]) #printing the dictionary after removing a key print(dict)
輸出
執行上述程式後會生成以下輸出。
{1: 'a', 2: 'b'}
{2: 'b'}
使用字典推導式
前面的技術在字典仍在使用時更新字典,這意味著鍵值對被刪除。如果我們需要保留原始鍵,我們可以使用自定義函式來實現。
眾所周知,Python 中的列表推導式可用於根據現有列表構建新列表。我們可以使用字典推導式對字典執行相同的操作。使用字典推導式,我們可以建立一個新的字典,其中包含一個排除我們不想要的值的條件,而不是從列表中刪除條目。
示例
以下示例使用字典推導式從 Python 字典中刪除鍵。
dict = {1: "a", 2: "b"} #printing dictionary before deletion print(dict) dict2 = {k: i for k, i in dict.items() if k != 1} #printing new dictionary print("dictionary after dictionary comprehension") print(dict2)
輸出
執行上述程式後會生成以下輸出。
{1: 'a', 2: 'b'}
dictionary after dictionary comprehension
{2: 'b'}
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP