Python 中字典是如何實現的?
Python 中的字典就像 C++ 和 Java 中的對映一樣。類似於對映的字典包含兩部分:第一部分是鍵,第二部分是值。字典本質上是動態的。建立字典後,您可以向其中新增更多鍵值對,也可以刪除字典中的鍵值對。您可以將另一個字典新增到當前建立的字典中。您還可以將列表新增到字典中,並將字典新增到列表中。
在字典中,您可以透過其相應的鍵訪問元素。
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”})
此函式將更新給定鍵的值
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP