如何從 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'}

更新於: 2022-09-16

815 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.