In this tutorial, you will learn about Python Hash. This is a built-in function that returns an object hash value. When looking at a dictionary, the hash value is an integer that is used to compare two dictionary keys easily.
In addition, a hash is a fixed-sized integer that serves as an indicator for a certain hash value. Each value must have its own hash.
Even if the value and the object are different, the value that will be received is still the same for that particular hash.
Also read: Python Import from Parent Directory in Simple Way
What is a hash in Python?
In Python, the hash method is a module that returns the hash value of an object. The hash method is used to return integers that can be used to compare dictionary keys using a dictionary lookup function. It requests an object hash(), which is set by default when the object is created by the user.
The following is the syntax for utilizing the hash method.
Python hash method parameters
The Python hash method only takes a single parameter.
Object: The object is a representation of a hash value that needs to be returned by the user. It can be in the form of an integer, string, or float.
Return value of a Python hash method
When the hash method is called, it returns an object hash value if that object is present. If the object has a custom hash value in a certain situation, the method truncates the hash value to the size of Py_ssize t.
Essential quality of good Python hash function
There are four essential qualities of a good Python hash function.
- The data being hashed determines entirely the value of the hash.
- All of the input data is used by the hash function.
- The data type is distributed equally across all possible hash by the hash function.
- The hash function creates different hash values for strings that are similar.
Hash method sample program
# hash for integer unchanged print('Hash for 212 is:', hash(212)) # hash for decimal print('Hash for 211.26 is:',hash(211.26)) # hash for string print('Hash for Python is:', hash('Python'))
Hash for 212 is: 212 Hash for 211.26 is: 599519182395539667 Hash for Python is: -3892058585827378993
Hash method sample program for immutable tuple objects
# tuple of vowels vowels = ('a', 'e', 'i', 'o', 'u') print('The hash is:', hash(vowels))
The hash is: 9168115093077197642
How does hash() work for custom objects?
As mentioned above, when the hash method is called, the hash function returns an object value if that object is present. It means that any object with a custom hash value can override it.
Always keep in mind that in order to get the right hash value, the method should always return an integer and should use both __eq__() as well as __hash__() to find the same value.
To understand the proper implementation of custom hash values, refer to the hash table below.
|Defined (by default)||Defined (by default)||If left as is, all objects compare unequal (except themselves)|
|(If mutable) Defined||Should not be defined||Implementation of hashable collection requires the key’s hash value to be immutable|
|Not defined||Should not be defined||If |
|Defined||Not defined||Class instances will not be usable as a hashable collection. __hash__() implicity set to |
|Defined||Retain from Parent|
|Defined||Doesn’t want to hash|
hash() for Custom Objects by overriding hash() sample programs
Program sample 1
class Person: def __init__(self, age, name): self.age = age self.name = name def __eq__(self, other): return self.age == other.age and self.name == other.name def __hash__(self): print('The hash is:') return hash((self.age, self.name)) person = Person(26, 'Glenn') print(hash(person))
The hash is: -8287381924158972941
The above example program does not need the __eq__() method to be implemented. All samples are created by default as hash objects.
Program sample 2
# Python 3 code to demonstrate # working of hash() # initializing objects int_val = 6 str_val = 'PythonIsBest' flt_val = 26.50 # Printing the hash values. # Notice Integer value doesn't change # You'l have answer later in article. print ("The integer hash value is : " + str(hash(int_val))) print ("The string hash value is : " + str(hash(str_val))) print ("The float hash value is : " + str(hash(flt_val)))
The integer hash value is : 6 The string hash value is : -8025239559631590002 The float hash value is : 1152921504606847002
Program sample 3
# Python 3 code to demonstrate # property of hash() # initializing objects # tuple are immutable tuple_val = (1, 2, 3, 4, 5) # list are mutable list_val = [1, 2, 3, 4, 5] # Printing the hash values. # Notice exception when trying # to convert mutable object print ("The tuple hash value is : " + str(hash(tuple_val))) print ("The list hash value is : " + str(hash(list_val)))
The tuple hash value is : -5659871693760987716 Traceback (most recent call last): File "<string>", line 12, in <module> TypeError: unhashable type: 'list'
The MD5 hash is a hash algorithm that turns inputs into a hash value with a fixed length of 128 bits (16 bytes).
- encode() – This function converts the string into acceptable bytes for hash functions.
- digest() – This function returns the data encoded into a byte format.
- hexdigets() – This function returns the data encoded into a hexadecimal format.
MD5 hash Sample Program
The sample program demonstrates an MD5 hash that accepts bytes and output as bytes in Python.
# # Python 3 code to demonstrate the data structures # working of MD5 (byte - byte) import hashlib # encoding PYTHONFORFREE using md5 hash # function result = hashlib.md5(b'PYTHONFORFREE') # printing the equivalent byte value. print("The byte equivalent of hash is : ", end ="") print(result.digest())
The byte equivalent of hash is : b'l\xf6\xd2u\x07e+\x0c0O\x91\xbb\x1e\xb3\x7fV'
The above sample program accepts bytes, which are accepted by the hash function. MD5 hash function. It is encoded by the md5 hash function, and then the message digest() function prints the byte-equivalent encoded string.
MD5 sample program which takes a string as input and output hexadecimal
# Python 3 code to demonstrate the # working of MD5 (string - hexadecimal) import hashlib # initializing string str2hash = "PYTHONFORFREE" # encoding PYTHONFORFREE using encode() # then sending to md5() result = hashlib.md5(str2hash.encode()) # printing the equivalent hexadecimal value. print("The hexadecimal equivalent of hash is : ", end ="") print(result.hexdigest())
The hexadecimal equivalent of hash is : 6cf6d27507652b0c304f91bb1eb37f56
Python Hash is one of the most useful modules in the Python library. Now that you know what it does and how to use it, we hope you will use it more often in your everyday coding.
I hope this lesson has helped you learn a lot. Check out our previous and latest articles for more life-changing tutorials that could help you a lot.