Skip to main content

Python HashMap Implementation Using Dictionary

In this tutorial you’ll learn how to implement hashmap in python using dictionary.

What is Hash Table or Hash Map?

In short, Hash table is a data structure which stores data in an associative manner. In this table, our data is stored in a array format, where each data value have a unique key to represent the data. So in this way, access of data becomes very fast if we know the key of the desired data. So in Hash Table, insertion and search operations are very fast irrespective of the size of the data.

How to Implement Hash Map in Python?

Well if you’re looking for implementation of hash map in python then the answer is Dictionary. Python Dictionary is a built-in type that supports key-value pairs. Basically Dictionary is like a list but instead of an integer index it can be of any type. Another thing to note that a dictionary is un-ordered, it may not show the items in the order it was defined. So in this article we’ll learn about dictionaries and all the operations that we can perform on a dictionary.

Python HashMap Implementation Using Dictionary

Creating a Dictionary

Let’s say we want to create a dictionary called phonebook where names will be used as keys and their phone numbers as values to the keys, then our code will be:

phonebook = {
        'name 1' : '9100000000',
        'name 2' : '9104043000',
        'name 3' : '9100004000',
}

Here phonebook  is the name of the dictionary and name 1, name 2 and name 3 are unique keys and each key represent to a phone number (data). Here the keys and data both are in string format but we can use any other datatype like int. 

Accessing Data from Dictionary

We can print all the entries by using for loop or we can print a specific value using its key. Let’s say we want access the phone number of name 1.

print(phonebook['name 1'])

Output:

9100004000

Or if you want to print all of the entries then the code will be.

for k,v in phonebook.items():
        print(k + " - " + v)

Output:

name 3 – 9100004000
name 2 – 9104043000
name 1 – 9100000000 

Here k and v are loop variables, where k is used for key and v is for their values.

Note: Dictionary can’t have duplicate entry. If more than one keys (having same name) are present in the dictionary then the last entry will be stored.

Add New Entry or Update Existing One Into Dictionary

phonebook['name 2'] = '0581234323' #updating existing entry
phonebook['name 4'] = '0681234323'      #creating a new entry

for k,v in phonebook.items():
        print(k+ " - " + v)

Output:

name 1 – 9100000000
name 4 – 0681234323
name 2 – 0581234323
name 3 – 9100004000

Here phonebook[key] = value can be used for both, to insert a new entry and also to update an existing entry. If the key is present in the dictionary then it will update the the value of that key with given value, if key doesn’t exist then It will add a new entry into the dictionary.

Deleting Entries from Dictionary

To delete a specific entry from the dictionary:

del phonebook['name 2']     #deleting a particular entry

for k,v in phonebook.items():
        print(k + " - " + v)

Output:

name 1 – 9100000000
name 3 – 9100004000

Here we’re deleting a particular entry from the dictionary phonebook using del statement.

Delete All Entries from Dictionary

phonebook.clear()  #deleting all the elements

print("phonebook  = " + str(phonebook))

Output:

phonebook  = {} 

Here clear() method is used to clear all the entries in dictionary. The dictionary will be empty.

Delete Entire Dictionary

del phonebook #deleting entire dictionary
print(phonebook)

Output:

NameError: name ‘phonebook’ is not defined

So del statement can be also used to delete the entire dictionary instead of a specific element.

Find Total Number of Entries in Dictionary

class_a = {1: 'Francis', 2: 'Mohan', 3: 'Steve'}

total_items = len(class_a) #Counting number of elements

print("No. of entries = " + str(total_items))

Output:

No. of entries = 3

Here class_a is a dictionary which have students roll numbers as keys and name as values. Now to count the number of entries, we’re using len() function here. Which will count the number of elements in the dictionary class_a and will return the number to the variable total_items.

There are several other methods used by dictionaries like:

Let’s say our dictionary name is dict.

  • dict.copy() – returns a copy of dictionary dict.
  • dict.keys() – returns a list of keys present in dict.
  • dict.values() – returns a list of values present in dict.
  • dict.items() – returns a list of tuple pairs (key values) present in dict.
  • cmp(dict1, dict2) – compare both of the dictionaries and returns true, false. The function cmp() can be used only in Python 2.

for more information on dictionaries in Python please visit https://docs.python.org/3/tutorial/datastructures.html

Comment below if you’ve any problem or suggestion related to python hashmap implementation using dictionary.

The post Python HashMap Implementation Using Dictionary appeared first on The Crazy Programmer.



from The Crazy Programmer https://www.thecrazyprogrammer.com/2018/06/python-hashmap.html

Comments

Popular posts from this blog

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan

R vs Python for Machine Learning

There are so many things to learn before to choose which language is good for Machine Learning. We will discuss each and everything about R as well as Python and the situation or problem in which situation we have to use which language. Let’s start Python and R are the two most Commonly used Programming Languages for Machine Learning and because of the popularity of both the languages Novice or you can say fresher are getting confused, whether they should choose R or Python language to commence their career in the Machine learning domain. Don’t worry guys through this article we will discuss R vs Python for Machine Learning. So, without exaggerating this article let’s get started. We will start it from the very Basics things or definitions. R vs Python for Machine Learning Introduction R is a programming language made by statisticians and data miners for statistical analysis and graphics supported by R foundation for statistical computing. R also provides high-quality graphics and

Top Tips For PCB Design Layout

Are you thinking about designing a printed circuit board? PCBs are quite complicated, and you need to make sure that the layout that you choose is going to operate as well as you want it to. For this reason, we have put together some top tips for PCB design layout. Keep reading if you would like to find out more about this. Leave Enough Space One of the most important design tips for PCB layout is that you need to make sure that you are leaving enough space between the components. While many people might think that packing components closely is the best route to take, this can cause problems further down the line. This is why we suggest leaving extra space for the wires that will spread. This way, you’ll have the perfect PCB design layout. Print Out Your Layout Struggling to find out if your components sizes match? Our next tip is to print out your layout and compare the printed version to your actual components. Datasheets can sometimes come with errors, so it doesn’t hurt to do