Python中的双向哈希表(双向字典)

时间:2024-07-04 18:12:28

我们知道Python中的数据结构中的字典,它以键:值对的形式保存数据。在本文中,我们将讨论Python中的双向哈希表或双向字典。我们可以说一个双向字典可以表示为键的值。双向字典的一个例子是:

示例:

dict={ 1 : 'Apple' , 2 : 'Google' , 3 : 'Microsoft'}

Input 1: 1
Output 1: Apple

Input 2: Microsoft
Output 2: 3

一个双向字典可以表示为关键字字典值。也就是说,它可以根据键返回值,也可以根据值返回相应的键。在上面的例子中,可以使用1,2,3来查找常规字典,这将分别返回Apple,Google和Microsoft。然而,在双向字典中,我们可以使用1,2和3以及Apple,Google和Microsoft分别返回1,2,3来查找字典。

实现过程

步骤1:安装bidict库

这个库使我们能够使用双向哈希表或双向字典。要安装bidict库,我们需要使用以下命令:

pip install bidict

步骤2:从bidict模块中调用bidict类

from bidict import bidict

步骤3:创建一个常规字典

在Python中创建字典很简单。我们将创建一个名为dict_it_fullforms的字典,它将常用的IT缩写形式映射到它们的完整形式。

dict_it_fullforms={'APK':'Android Application Package',
				'CPU':'Central Processing Unit',
				'SMS':'Short Message Service',
				'USB':'Universal Serial Bus',
				'WIFI':'Wireless Fidelity',
				'WWW':'World Wide Web'}

步骤4:创建一个bidict对象

通过使用dict_it_fullforms创建bidict对象。

bidict_it_fullforms = bidict(dict_it_fullforms)

步骤5:打印字典对象值

这里我们使用键来打印bidict_it_fullforms的值。

print(bidict_it_fullforms['APK'])
print(bidict_it_fullforms['SMS'])
print(bidict_it_fullforms['WIFI'])

输出

Android Application Package
Short Message Service
Wireless Fidelity

步骤6:bidict对象的Inverse属性

bidict_it_shortforms = bidict_it_fullforms.inverse

步骤7:查看完整键值对
我们现在有了bidict_it_shortforms作为bidict对象引用,它可用于使用值检索键。因此,我们可以使用完整的形式来获得键值对。

print(bidict_it_shortforms['Central Processing Unit'])
print(bidict_it_shortforms['Universal Serial Bus'])
print(bidict_it_shortforms['World Wide Web'])

输出

CPU
USB
WWW

步骤8:修改或添加

如果对bidict_it_shortforms进行了任何更改或键值添加,它将反映在bidict_it_fullforms中,反之亦然。让我们添加SIM的完整形式。

bidict_it_shortforms['Subscriber Identity Module']='SIM'
print(bidict_it_fullforms['SIM'])

输出

Subscriber Identity Module

完整代码

# Python implementation for bidirectional 
# hash table or two way dictionary.

# import the bidict class of the bidict module
from bidict import bidict

# creating a dictionary mapping commonly used 
# IT short forms to their full forms
dict_it_fullforms = {'APK': 'Android Application Package', 
					'CPU': 'Central Processing Unit',
					'SMS': 'Short Message Service', 
					'USB': 'Universal Serial Bus', 
					'WIFI': 'Wireless Fidelity', 
					'WWW': 'World Wide Web'}

# Creating a bidict object
bidict_it_fullforms = bidict(dict_it_fullforms)

# Lookup using short forms
print(bidict_it_fullforms['APK'])
print(bidict_it_fullforms['SMS'])
print(bidict_it_fullforms['WIFI'])

# Inverse attribute of bidict object
bidict_it_shortforms = bidict_it_fullforms.inverse

# Lookup using full forms
print(bidict_it_shortforms['Central Processing Unit'])
print(bidict_it_shortforms['Universal Serial Bus'])
print(bidict_it_shortforms['World Wide Web'])

# Adding SIM : Subscriber Identity Module to the bi-dictionary
bidict_it_shortforms['Subscriber Identity Module'] = 'SIM'
print(bidict_it_fullforms['SIM'])

输出

Android Application Package
Short Message Service
Wireless Fidelity
CPU
USB
WWW
Subscriber Identity Module