We know about Python dictionaries in a data structure in Python which holds data in the form of key: value pairs. In this article, we will discuss the Bidirectional Hash table or Two-way dictionary in Python. We can say a two-way dictionary can be represented as key ⇐⇒ value. One example of two-way dictionaries is:
Example:
dict={ 1 : 'Apple' , 2 : 'Google' , 3 : 'Microsoft'} Input 1: 1 Output 1: Apple Input 2: Microsoft Output 2: 3 Explaination:The above dictionary maps the keys ( integers) to the values (company names) in this case.
A bidirectional dictionary can be represented as key ⇐⇒ value. I.e. it can return value based on the key and also the corresponding key on the basis of the value. In the above example, a regular dictionary can be looked up using 1,2,3 which would return Apple, Google, and Microsoft respectively. However in a bidirectional dictionary, we can look up the dictionary using 1,2, and 3 as well as Apple, Google, and Microsoft which would return 1,2,3 respectively.
Stepwise Implementation
Step 1: Installing the bidict library.
This library enables us to work with bidirectional hash tables or two-way dictionaries. To install the bidict library we need to use the following command:
pip install bidict
Step 2: Importing the bidict class from the bidict module
Python
|
Step 3: Create a regular dictionary.
Creating a dictionary in python is simple. We will be creating a dictionary called dict_it_fullforms which maps the commonly used IT short forms to their full forms.
Python3
|
Step 4: Creating a bidict object
Create a 2-way dictionary by creating a bidict object bidict_it_fullforms using dict_it_fullforms.
Python3
|
Step 5: Lookup using short forms
Here we use the keys to print the values of bidict_it_fullforms.
Python3
|
Output:
Android Application Package Short Message Service Wireless Fidelity
Step 6: An Inverse attribute of bidict object
In order to get the keys of respective full forms we need to use an inverse attribute of the bidict_it_fullforms object.
Python3
|
Step 7: Lookup using full forms
We now have bidict_it_shortforms as a bidict object reference that can be used to retrieve keys using values. Hence we can get the short forms using the full forms.
Python3
|
Output:
CPU USB WWW
Step 8: Changes or Additions
If any changes or key-value additions are made to bidict_it_shortforms it will reflect in bidict_it_fullforms and vice versa. Let us add the full form of SIM.
Python3
|
Output:
Subscriber Identity Module
Complete Code:
Python3
|
Output:
Android Application Package Short Message Service Wireless Fidelity CPU USB WWW Subscriber Identity Module