Python哈希表(Hash)

Python哈希表(Hash) 首页 / 数据结构入门教程 / Python哈希表(Hash)

哈希表(Hash Table)是一种数据结构,其中数据元素的地址或索引值是从哈希函数生成的,由于索引值充当数据值的键,因此可以更快地访问数据。

访问元素

要访问字典元素,您可以使用熟悉的方括号和键来获取其值。

链接:https://www.learnfk.comhttps://www.learnfk.com/python-data-structure/python-hash-table.html

来源:LearnFk无涯教程网

# 声明字典
dict={'Name': 'Learnfk', 'Age': 7, 'Class': 'First'}

# 用它的键访问字典
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

执行以上代码后,将产生以下输出-

无涯教程网

dict['Name']:  Learnfk
dict['Age']:  7

更新字典

您可以通过添加新元素或键值对来更新字典, 修改现有元素,或删除现有元素,如下面的简单示例所示-

# 声明字典
dict={'Name': 'Learnfk', 'Age': 7, 'Class': 'First'}
dict['Age']=8; # 更新现有元素
dict['School']="DPS School"; #添加新元素
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

执行以上代码后,将产生以下输出-

无涯教程网

dict['Age']:  8
dict['School']:  DPS School

删除元素

您可以删除单个词典元素,也可以清除词典的全部内容。要显式删除整个字典,只需使用del语句。-

dict={'Name': 'Learnfk', 'Age': 7, 'Class': 'First'}
del dict['Name']; # 使用键“Name”删除条目
dict.clear();     # 删除dict中的所有条目
del dict ;        # 删除整个字典

print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

这将产生以下输出。请注意,引发异常是因为在del dict字典之后不再存在-

dict['Age']:
Traceback (most recent call last):
   File "test.py", line 8, in 
      print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
 

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

超级访谈:对话道哥 -〔吴翰清(道哥)〕

PPT设计进阶 · 从基础操作到高级创意 -〔李金宝(Bobbie)〕

结构会议力 -〔李忠秋〕

现代React Web开发实战 -〔宋一玮〕

玩转Vue 3全家桶 -〔大圣〕

性能优化高手课 -〔尉刚强〕

设计模式之美 -〔王争〕

Spring Boot与Kubernetes云原生微服务实践 -〔杨波〕

从0开始学微服务 -〔胡忠想〕

好记忆不如烂笔头。留下您的足迹吧 :)