在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 dictionaryDictionary[3] = "Cat"# element with key value 3 is update with value “Cat”
删除字典中的元素
Dictionary.pop(3)# Delete element with key value 3del Dictionary[4]# delete element with key value 4Dictionary.popitem()# delete last inserted element in dictionarydel Dictionary# this will delete whole dictionary
在Python中字典的内置函数
Dictionary_2 = Dictionary.copy()
立即学习“Python免费学习笔记(深入)”;
这个复制函数将把字典的所有值复制到Dictionary_2中
Dictionary.clear()
clear()函数将清空整个字典。
Dictionary.get(2)
get()函数将返回键2的值。
Dictionary.values()
此函数将返回字典的所有值。
Dictionary.update({5:”Ears”})
这个函数将更新给定键的值