Python 字典是如何实现的

Python 字典是如何实现的

字典在Python中就像C++和Java中的映射(map)一样。像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()

copy()函数将复制字典的所有值到Dictionary_2。

  • Dictionary.clear()

clear()函数将清空整个字典。

  • Dictionary.get(2)

get()函数将返回key为2的值。

  • Dictionary.values()

该函数将返回字典的所有值。

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

该函数将更新给定key的值。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程