Python 中如何实现字典?
pythonserver side programmingprogramming更新于 2024/2/16 11:45:00
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"
Delete element in Dictionary
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"})
此函数将更新给定的值关键