Python 字典中 update 方法的用法是什麼?


update 方法是字典資料結構的方法之一。它用於更新已建立字典中的值,這意味著它向字典新增新的鍵值對。更新的鍵和值將更新到最後。

字典由花括號{}表示。字典包含鍵值對,統稱為專案,可以接受任何資料型別的元素作為值。它是可變的,這意味著一旦建立了字典,我們就可以應用更改。

它有以冒號分隔的鍵值對,字典中的鍵和值統稱為專案。鍵是唯一的,而值可以有重複。索引不適用於字典,如果我們想訪問一個值,我們必須使用一個鍵,當我們想訪問特定的鍵值時,則需要同時使用鍵和索引。

語法

以下是使用字典的 update 方法的語法。

d_name.update({k1:v1})

其中,

  • d_name 是字典的名稱

  • update 是方法名稱

  • k1 是鍵

  • v1 是值

示例

當我們在 update 函式中傳遞鍵值對時,這些定義的鍵和值將更新到字典中。

我們建立了一個帶有鍵和值的字典,並將結果賦值給變數 d1。然後我們透過呼叫它的名稱 d1 列印了這個字典。之後,我們使用 update 方法用新的鍵值對更新了 d1。最後,我們列印了結果字典以便將其與原始版本進行比較。

d1 = {"a":10,"b":20,"c":30}
print("The created dictionary:",d1)
d1.update({"d":40})
print("The updated dictionary:",d1)

輸出

以下是字典的 update 方法的輸出。我們可以觀察到專案更新到字典的末尾。

The created dictionary: {'a': 10, 'b': 20, 'c': 30}
The updated dictionary: {'a': 10, 'b': 20, 'c': 30, 'd': 40}

示例

這是另一個使用 update 函式更新字典專案的示例。以下是程式碼。

d1 = {"a":10,"b":20,"c":30}
print("The created dictionary:",d1)
d1.update({"c":25})
print("The updated dictionary:",d1)

輸出

The created dictionary: {'a': 10, 'b': 20, 'c': 30}
The updated dictionary: {'a': 10, 'b': 20, 'c': 25}

示例

在這個示例中,當我們將多個專案傳遞給字典時,字典將使用這些專案進行更新。

d1 = {"a":10,"b":20,"c":30}
print("The created dictionary:",d1)
d1.update({"c":25,"d":40})
print("The updated dictionary:",d1)

輸出

The created dictionary: {'a': 10, 'b': 20, 'c': 30}
The updated dictionary: {'a': 10, 'b': 20, 'c': 25, 'd': 40}

示例

這是另一個瞭解 update 方法以更新字典中多個專案的示例。以下是程式碼。

d1 = {"a":10,"b":20,"c":30}
print("The created dictionary:",d1)
d1.update({"d":40,"e":50,"f":50})
print("The updated dictionary:",d1)

輸出

The created dictionary: {'a': 10, 'b': 20, 'c': 30}
The updated dictionary: {'a': 10, 'b': 20, 'c': 30, 'd': 40, 'e': 50, 'f': 50}

更新於: 2023年5月15日

344 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告