首頁  >  文章  >  後端開發  >  在Python中,字典是如何實現的?

在Python中,字典是如何實現的?

WBOY
WBOY轉載
2023-08-18 22:01:08663瀏覽

在Python中,字典是如何實現的?

在Python中,字典就像C 和Java中的映射。像Map字典一樣,它由兩個部分組成:鍵和值。字典是動態的,你可以在建立字典後加入更多的鍵和值,也可以從字典中刪除鍵和值。你可以將另一個字典加入到目前建立的字典中。也可以將清單加入字典中,將字典加入到清單中。

在字典中,您可以透過它們各自的鍵來存取元素。

Dictionary = {
   1: "Apple", 2: "Ball", 3: "Caterpillar", 4: "Doctor",
   5: "Elephant"
}

在這裡,字典1、2、3 ... 代表鍵,而“Apple”、“Ball”、“Caterpillar” ... 代表值。

Dictionary = {
   Key: "Value",
   Key : "Value", . . . . . Key : "Value"
}

訪問元素

print(dictionary[1])
#print element whose key value is 1 i.e. “Apple”

print(dictionary[4])
# print element whose key value is 4 “Doctor”

在字典中插入和更新元素

Dictionary[6] = "Flesh"
# inserting element with key value 6 at last in dictionary

Dictionary[3] = "Cat"
# element with key value 3 is update with value “Cat”

刪除字典中的元素

Dictionary.pop(3)
# Delete element with key value 3

del Dictionary[4]
# delete element with key value 4

Dictionary.popitem()
# delete last inserted element in dictionary

del Dictionary
# this will delete whole dictionary

在Python中字典的內建函數

  • Dictionary_2 = Dictionary.copy()

    #這個複製函式將會把字典的所有值複製到Dictionary_2中

  • Dictionary.clear()

    #clear()函數將清空整個字典。

  • Dictionary.get(2)

    #get()函數將傳回鍵2的值。

  • Dictionary.values()

    #此函數將傳回字典的所有值。

  • Dictionary.update({5:”Ears”})

    #這個函數將會更新給定鍵的值

以上是在Python中,字典是如何實現的?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除