在字典中,您可以通过它们各自的键访问元素。
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()
这个复制函数将把字典的所有值复制到dictionary_2中
dictionary.clear()
clear()函数将清空整个字典。
dictionary.get(2)
get()函数将返回键2的值。
dictionary.values()
此函数将返回字典的所有值。
dictionary.update({5:”ears”})
这个函数将更新给定键的值
以上就是在python中,字典是如何实现的?的详细内容。
