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