python tutorial - Python Hashing (Hash Tables And Hashlib) - learn python - python programming
- While an array can be used to construct hash tables, array indexes its elements using integers.
- However, if we want to store data and use keys other than integer, such as 'string', we may want to use dictionary.
- Dictionaries in Python are implemented using hash tables. It is an array whose indexes are obtained using a hash function on the keys.
- We declare an empty dictionary like this:
- Then, we can add its elements:
- It's a structure with (key, value) pair:
- The string used to "index" the hash table D is called the "key". To access the data stored in the table, we need to know the key:
How we loop through the hash table ?
- If we want to print the (key, value) pair:
Hashing from two arrays
- Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are associated with the elements of the other (the values):
- Here are some hashing samples using built-in hash function:
- As we can see from the example, Python is using different hash() function depending on the type of data.
- Python provides hashlib for secure hashes and message digests:
Hashing Sample Code
- In this section, we used 64 bit integer (hash value from hash()) for the comparison of shingles instead of directly working on the string.
- Output is exactly the same as the one we got using string comparison: