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日

345 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.