In python, the built-in function hash()is used to obtain the hash value of the given object. To compare dictionary keys while a dictionary lookup these integer hash values are used. Actually the hash() method calls __hash__()
method of an object.
Hashable types: * bool * int * long * float * string * Unicode * tuple * code object
Non-hashable types: * bytearray * list * set * dictionary * memoryview
hash(object) #Where object can be integer, string, float etc.
Takes a single parameter. Numeric values which are equal will have the same hash value irrespective of their data types.
Parameter | Description | Required / Optional |
---|---|---|
object | the object whose hash value is to be returned (integer, string, float) | Optional |
hash() method returns the hash value of an object if it has one. The object with custom __hash__()
method, it truncates the return value to the size of Py_ssize_t.
Input | Return Value |
---|---|
object | Hash value |
# hash for integer unchanged
print('Hash for 181 is:', hash(181))
# hash for decimal
print('Hash for 181.23 is:',hash(181.23))
# hash for string
print('Hash for Python is:', hash('Python'))
Output:
Hash for 181 is: 181 Hash for 181.23 is: 530343892119126197 Hash for Python is: 2230730083538390373
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
print('The hash is:', hash(vowels))
Output:
The hash is: -695778075465126279
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))
pers 'Adam')
print(hash(person))
Output:
The hash is: 3785419240612877014