Day 6 of Python (Dictionary, Set and Hashing)
Source: Dev.to
Dictionary
It is a collection used to store data in key:value pairs and it is a built-in data type, mutable and ordered.
id = {
"name": "Vidya",
"age": 21,
"location": "Chennai",
"gender": "Female"
}
print(id)
Output
{'name': 'Vidya', 'age': 21, 'location': 'Chennai', 'gender': 'Female'}
Set
It is a collection of items which is unordered, does not allow duplicate values and is mutable.
num = [1, 1, 2, 2, 2, 3, 3, 5, 5, 5]
freq = {}
for i in num:
if i in freq:
freq[i] = freq[i] + 1
else:
freq[i] = 1
print(freq)
Output
{1: 2, 2: 3, 3: 2, 5: 1}
Hashing
It is a technique that takes a key and converts it into a fixed integer value (hash value). This hash value is used to decide where to store and quickly retrieve data in memory.
print(hash("Vidya"))
Output
45823984723984
Hash collision
Sometimes two different keys produce the same hash, which causes a collision. Common strategies to handle collisions include open addressing and probing.