Python语言基础
Python语言进阶
Python数据结构

Python 哈希表

Python 哈希表详细操作教程
哈希表是一种数据结构,其中数据元素的地址或索引值是从哈希函数生成的。由于索引值充当数据值的键,因此可以更快地访问数据。换句话说,哈希表存储键值对,但是键是通过哈希函数生成的。
因此,随着键值本身成为存储数据的数组的索引,数据元素的搜索和插入功能变得更快。
在Python中,Dictionary数据类型表示哈希表的实现。词典中的键满足以下要求。
字典的键是可哈希的,即由哈希函数生成,哈希函数为提供给哈希函数的每个唯一值生成唯一结果。 字典中数据元素的顺序不固定。
要访问字典元素,您可以使用熟悉的方括号和键来获取其值。

在字典中访问值

要访问字典元素,您可以使用熟悉的方括号和键来获取其值。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
# 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

更新字典

您可以通过添加新条目或键值对,修改现有条目或删除现有条目来更新字典,如下面的简单示例所示:
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
# 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语句。-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
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
    
       print "dict['Age ']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
    
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4