Python hash() Function

Python’s hash() function can be used for converting any value to a unique integer. For example – If you have a tuple a_tuple = (1, 2, 3) then hash(a_tuple) will return some number like 529344067295497451. This large number is said to be hash value of a_tuple.
Quite simple, no complexity just a function hash(). But wait Why is hashing needed in Python?
To do lookup for data inside dictionary/set or any other immutable python object quickly.

Like if you’ve a dictionary and you want to check wether it have some specific key or not. For doing this lookup of a key inside dictionary there exist 3 methods – in operator, keys() function, get() function.

If your not aware of 3 Ways to

Let’s pick in operator and use it for looking up some key in a dictionary.

# Defining a Python Dictionary
dict1 = {1:"Computer", 2:"Science", 3:"Hub"}

1 in dict1              # Returns true
5 in dict1              # Returns false

Let’s try to understand How does in operator works? Python would loop around keys of Dictionary and will match each key against key specific by in operator. If python finds some match then it will true or false otherwise. This process of match key itself with other keys in dictionary can take long time as keys can be Complex Objects. That’s why in order to reduce time of comparing objects, hashes are used.
So Python for doing key lookup inside Dictionary will first convert key specific by in operator to hash value and all keys inside Dictionary to also their equivalent hash values. After this Python will compare hash values of all keys inside dictionary to specified key, if some match of hash values it found. Then that means specified key does exist inside Dictionary.

Hashing just reduces time taken to compare objects

Hashable Python Data Types

Below is a table listing all of Python Data Types which are hashable, most of immutable data types fall under this category.

Tuples
Dictionaries
Sets

Code Examples Showing use of hash() function

# hash for integer unchanged
print('Hash for 67 is:', hash(67))           # Returns 

# hash for decimal
print('Hash for 8191.113 is:',hash(8191.113))

# hash for string
print('Hash for ComputerScienceHub is:', hash('ComputerScienceHub'))

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts