Hash maps in python

Hashmap in Python

Python Certification Course: Master the essentials

Data is accessed and stored in a variety of ways. Hash tables are an important type of data. Dictionary, or the built-in data type , is used to access hash tables. In this data structure the information is stored in the form of key-value pairs. Key can be used as a reference to retrieve the stored data from the hash table. Due to this reason the hashmap table is also know as the look-up table data structure.

Introduction

In computer science, a hash table, also known as a hashmap , is one type of data structure which maps the keys to value pairs. It works by calculating an index value with a function, and then storing the elements to be searched, removed, inserted and etc. This simplifies and accelerates data access. Key-value pairs are stored in hash tables, with the key generated using a hash function.

Hash tables and has maps are implemented using Python’s built-in dictionary data type.

The keys of a dictionary are generated via a hashing function in Python. The elements of a dictionary are not sorted and can be changed. The names of employees and their IDs, or the names of students and their IDs, are mapped.

Читайте также:  Python requests http response

Hash table vs Hashmap

Let’s look at the differences between the hash table and hashmap in Python now.

Hash Table HashMap
Allows for one null key and many null values. There are no null keys or values allowed.
Fast Slow
Synchronized Non-Synchronized

Design HashMap in Python

Let’s say we want to create a HashMap that doesn’t use any of the built-in hash table libraries. The following are the various functions that will be available:

  • get_val(key) : This function returns the value to which the given key is mapped, or «No record found» if no mapping for the key exists in this map.
  • set_val(key,val) : A key-value pair is added to the hash map. Update the value if it already exist in the hash map.
  • delete_val(key) : If the hash map already has the mapping for the key, this method removes it.

Understanding HashMap

In Python, there are two ways to create and initialise dictionaries. Some of them are as follows:

Let’s have a look at the initial strategy.

The code above returns a type dictionary after creating a new dict dictionary.

Now let’s have a look on another approach to create a dictionary.

Let’s look at some of the operations that dictionaries can perform.

How to Use Key Values?

The values of a dictionary can be accessed by typing the dictionary’s name into a square box, followed by the key name. For example, simple dict[Name] will return the value that is Aditya , sample [Age], for example, will yield a value that is 22 , and so on.

Functions to be used

Another way to acquire the values of a dictionary is to use a combination of built-in functions. A dictionary, for example, is shown below.

The function sample_dict.keys() returns a list of all the current keys in the dictionary. The output in this case will be Name, Age, and City .

Sample_dict.values() , on the other hand, returns all of the dictionary’s values for each key. In this scenario, Aditya , 22 and Las-Vegas will be the results.

Finally, to get values, use the get() command. For example, sample_dict.get(Name) will return the value Aditya .

Making use of Loops

Another way to extract values from a dictionary is to use loops to iterate through them. Consider the following example from the previous dictionary:

Let’s go over this dictionary again.

All of the keys in the dictionary are printed out using the lines of code above.

All of the values of dictionary’s keys are printed by using the code above. Last but not least:

The above lines of code prints all of the elements in the dictionary’s key and value.

Changes to dictionary values are possible. Because dictionaries are mutable, their entries can be changed as needed. For example, if I want to change City in sample dict from Las-Vegas to Los-Angeles , I can do so in the following ways:

Delete entries of a dictionary

There are a few ways to remove items from a dictionary. To delete an entire item or a key and value pair, for example, we can use the below line of code.

This above line of code will remove Name: Aditya pair from the dictionary.

Just the value, not the key, can be deleted with the pop() function.

The above code removes the key element while preserving the value of the Name key. You’re probably wondering what the current value of Name’s key is. It currently corresponds to a null value.

There’s also a way to remove the most lately entered entry from the dictionary. This can be accomplished with the popitem() method.

clear() function can be used to clear all items of the dictionay. Using sample to clear the dictionary. All entries in the dictionary are removed using clear() .

Time Complexity

It takes the same amount of time to hash and access memory indexes. As a result, the search difficulty of a hash map is constant time that is O(1) time.

Conclusion

  • Hashmap in python are used for fast insertion, deletion and look-up.
  • It has the high storage capacity that is it can store the large datasets with high number of items.
  • Value of the corresponding keys can be accessed very quickly using built-in functions.
  • Hashmaps can be sorted using lambda and itemgetter functions.

Источник

Hash tables and Hash maps in Python

Data requires multiple ways to be accessed or stored. Hash Tables and Hashmaps happen to be the best data structures to implement this in Python via the built-in data type known as a dictionary.

A Hashmap or a Hash table in data structure maps keys to its value pairs and uses a function that computes any index value holding the elements to be inserted, searched, or removed. This helps make data access easier and faster. Hash tables generally store key-value pairs and use the hash function for generating a key.

In this article, you will learn what Hash Tables and Hashmaps are and how they are implemented in Python.

Learn data science to gain edge over your competitors

Ads of upGrad blog

What is a Hash table or a Hashmap Python?

A hash table or hashmap Python is an indexed data structure. It uses hash functions to compute an index by using a key into an array of slots or buckets. You can map its value to a bucket using the corresponding index, and the key is immutable and unique.

Hashmaps are similar to a cabinet of drawers labeled with the things they store. For instance, hashmaps can store user information like the first and last name, etc., in the bucket.

The hash function is integral for the implementation of a hashmap. It uses the key and translates it to the bucket’s index in the bucket list. Ideal hashing produces a separate index for every key. However, keep in mind that collisions can occur. When hashing produces an already existing index, a bucket for multiple values can be easily used by rehashing or appending a list. In Python, an example of hash maps is dictionaries.

Let us look into the hashmap implementation in detail to learn how to customize and build data structures for search optimization.

Hashmap in Python

The hashmap includes the following functions:

  • set_val(key, value): This function is used for inserting a key-value pair into the hash map. If there is already an existing value in the hash map, you must update the value.
  • get_val(key): This function returns the value to the specified key that is mapped or “No record found” if this map has no mapping for the key.
  • delete_val(key): Deletes the mapping for the particular key if the hashmap has the mapping for the key.

# Create empty bucket list of given size

return [[] for _ in range(self.size)]

# Insert values into hash map

# Get the index from the key

hashed_key = hash(key) % self.size

# Get the bucket corresponding to index

for index, record in enumerate(bucket):

record_key, record_val = record

# check if the bucket has same key as

# If the bucket has same key as the key to be inserted,

# Otherwise append the new key-value pair to the bucket

# Return searched value with specific key

# Get the index from the key using

hashed_key = hash(key) % self.size

# Get the bucket corresponding to index

for index, record in enumerate(bucket):

record_key, record_val = record

# check if the bucket has same key as

# If the bucket has same key as the key being searched,

# Otherwise indicate there was no record found

# Remove a value with specific key

# Get the index from the key using

hashed_key = hash(key) % self.size

# Get the bucket corresponding to index

for index, record in enumerate(bucket):

record_key, record_val = record

# check if the bucket has same key as

# To print the items of hash map

return “”.join(str(item) for item in self.hash_table)

hash_table.set_val(upGrad@example.com’, ‘some value’)

hash_table.set_val(‘portal@example.com’, ‘some other value’)

# search/access a record with key

Check our US — Data Science Programs

Performing Operations on Hash tables using Dictionaries:

There are numerous operations that can be performed in Python on hash tables via dictionaries. They are as follows:-

Accessing Values:

You can easily access the values of a dictionary in the following ways:-

Using key values:

You can access dictionary values using the key values like below:-

Using functions:

There are numerous built-in functions such as get(), keys(), values(), etc.

Implementing the for loop:

The loop gives you access to the the key-value pairs of a dictionary by iterating over them. For example:

print(x, “:” , y) #prints keys and values

Updating Values:

Dictionaries are mutable data types that can be updated when required. You can do as follows:-

my_dict[‘Olaf’] = ‘004’ #Updating the value of Dave

my_dict[‘Kristoff’] = ‘005’ #adding a key-value pair

Deleting items from a dictionary:

You can delete items from a dictionary with functions like del(), pop(), popitem(), clear(), etc. For example:

del my_dict[‘Elsa’] #removes key-value pair of ‘Elsa’

my_dict.pop(‘Anna’) #removes the value of ‘Anna’

my_dict.popitem() #removes the last inserted item

Conclusion

We can easily conclude that hashmaps and hash table Python are integral for easier and faster access to relevant data. It is a valuable tool for data science professionals like data scientists and data analysts. If you are interested in learning more about the field of Data Science, upGrad has the best Professional Certificate Program in Data Science for Business Decision Making .

Источник

Оцените статью