-
Hajipur, Bihar, 844101
A Hash Table is a data structure that stores data in key-value pairs. In Python, the built-in dict
(dictionary) is the most common way to implement a hash table.
Hash tables use a hash function to map keys to a specific index where the value is stored.
# Create a hash table (dictionary)
students = {
"101": "Alice",
"102": "Bob",
"103": "Charlie"
}
print(students["102"]) # Output: Bob
✅ Keys can be strings, numbers, or tuples
✅ Values can be of any data type
students["104"] = "David"
students["103"] = "Eve"
del students["101"]
for key, value in students.items():
print(key, ":", value)
Method | Description |
---|---|
dict.get(key) |
Returns value for key (or None ) |
dict.keys() |
Returns all keys |
dict.values() |
Returns all values |
dict.items() |
Returns all key-value pairs |
dict.pop(key) |
Removes item by key |
key in dict |
Checks if key exists |
print(hash("apple")) # Outputs an integer (hash value)
Python internally uses this hash value to store keys efficiently.
Storing user profiles
Phonebooks
Caching
Counting items (frequency maps)
Lookup tables
Q1. Write a Python program to create a dictionary of employee ID → name.
Q2. Write a Python program to add a new employee to the dictionary.
Q3. Write a Python program to update the name of an existing employee.
Q4. Write a Python program to delete an employee using del
keyword.
Q5. Write a Python program to check if the key "105"
exists in the dictionary.
Q6. Write a Python program to use a loop to print all keys and values in the dictionary.
Q7. Write a Python program to get the value for key "104"
using .get()
.
Q8. Write a Python program to list all keys using the .keys()
method.
Q9. Write a Python program to remove an item from the dictionary using .pop()
.
Q10. Write a Python program to count the number of items in the dictionary using len()
.
Q1: Which Python data type is used as a hash table?
Q2: What do hash tables store data as?
Q3: What is the time complexity of accessing a value by key in a dictionary?
Q4: What does dict.get(key) return if the key doesn't exist?
Q5: How do you remove a key-value pair from a dictionary?
Q6: What does dict.items() return?
Q7: What is a hash function used for in a hash table?
Q8: Which keyword checks if a key exists in a dictionary?
Q9: Which method returns only keys from a dictionary?
Q10: What will len(dict) return?