目录

Python - Hash Table

散列表是一种数据结构,其中数据元素的地址或索引值是从散列函数生成的。 这使得访问数据的速度更快,因为索引值表现为数据值的关键。 换句话说,Hash表存储键值对,但键是通过散列函数生成的。

因此,当键值本身成为存储数据的数组的索引时,数据元素的搜索和插入功能变得更快。

在Python中,Dictionary数据类型表示哈希表的实现。 字典中的键满足以下要求。

  • 字典的键是可清除的,即由散列函数生成,散列函数为提供给散列函数的每个唯一值生成唯一的结果。
  • 字典中数据元素的顺序不固定。

所以我们通过使用如下的字典数据类型看到哈希表的实现。

访问字典中的值

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

# Declare a dictionary 
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
# Accessing the dictionary with its key
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

执行上述代码时,会产生以下结果 -

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

更新字典

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

# Declare a dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

执行上述代码时,会产生以下结果 -

When the above code is executed, it produces the following result −
dict['Age']:  8
dict['School']:  DPS School

删除字典元素

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

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
del dict ;        # delete entire dictionary
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 <module>
      print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
 </module>
↑回到顶部↑
WIKI教程 @2018