DICT¶
In Python, the term "hashable" is used to describe an object that has a hash value that remains constant during its lifetime. In the context of dictionaries, hashable objects are critical because they are used as keys.
What Does Hashable Mean?¶
-
Hash Value:
A hash value is a fixed-size integer that uniquely identifies an object, generated by thehash()
function. -
Immutability:
To be hashable, an object must be immutable. This ensures that its hash value does not change over time, which is a key requirement for dictionary keys. -
Equality and Hashing:
Hashable objects must implement the__hash__()
method to compute the hash value and the__eq__()
method for equality checks. Python dictionaries use these methods to organize and retrieve keys efficiently.
Why Hashable Is Important for Dictionaries¶
-
Key Uniqueness:
Dictionary keys must be unique. Python uses the hash value of a key to quickly determine where to store or find a value in the dictionary. -
Efficient Lookups:
The hash value allows the dictionary to find a key in O(1) time complexity on average.
Hashable Objects¶
Objects that are immutable (and hence hashable) include:
- Strings:
- Numbers (int, float, etc.):
- Tuples (if all elements are hashable):
Unhashable Objects¶
Objects that are mutable (and hence not hashable) include:
- Lists:
Lists are mutable and cannot be used as dictionary keys.
- Sets:
Like lists, sets are mutable and unhashable.
Custom Hashable Objects¶
You can make a custom object hashable by defining the __hash__()
and __eq__()
methods.
Example¶
class MyHashableClass:
def __init__(self, value):
self.value = value
def __hash__(self):
return hash(self.value) # Use the hash of 'value'
def __eq__(self, other):
return isinstance(other, MyHashableClass) and self.value == other.value
# Using custom hashable object as dictionary key
key = MyHashableClass(42)
my_dict = {key: "Custom Object"}
print(my_dict[key]) # Output: Custom Object
Key Points in the Context of Dictionaries¶
- A dictionary key must be hashable.
- Hashable objects allow Python to store dictionary keys in a hash table for fast lookups.
- If you attempt to use an unhashable object as a key, Python will raise a
TypeError
.
Example¶
# Hashable example
hashable_key = "name"
my_dict = {hashable_key: "Alice"}
print(my_dict[hashable_key]) # Output: Alice
# Unhashable example
unhashable_key = [1, 2, 3] # A list
my_dict = {unhashable_key: "List"} # Raises TypeError
By ensuring that objects used as dictionary keys are hashable, Python maintains the efficiency and reliability of its dictionary implementation.
๐ Python Dictionary Data Structure¶
In Python, List
, Tuple
, and Set
are used to represent a group of individual objects as a single entity.
However, if we want to represent a group of objects as key-value pairs, we should use a Dictionary.
Examples of Dictionary Use Cases¶
rollno โ name
phone number โ address
IP address โ domain name
๐ Key Characteristics of Dictionaries¶
- Duplicate keys are not allowed, but values can be duplicated.
- Heterogeneous objects are allowed as both keys and values.
- Insertion order is preserved (since Python 3.7+).
- Dictionaries are mutable (modifiable).
- Dictionaries are dynamic (can grow/shrink in size).
- Indexing and slicing are not applicable.
-
In other languages:
-
Known as Map in C++ and Java.
- Known as Hash in Perl and Ruby.
๐ ๏ธ Creating a Dictionary¶
Creating an Empty Dictionary¶
Adding Elements¶
d[100] = "Durga"
d[200] = "Ravi"
d[300] = "Shiva"
print(d)
# Output: {100: 'Durga', 200: 'Ravi', 300: 'Shiva'}
Creating with Predefined Data¶
๐ Accessing Dictionary Elements¶
d = {100: 'Durga', 200: 'Ravi', 300: 'Shiva'}
print(d[100]) # Output: Durga
print(d[300]) # Output: Shiva
Handling Missing Keys¶
๐งช Program: Store and Display Student Records¶
rec = {}
n = int(input("Enter number of students: "))
for i in range(n):
name = input("Enter Student Name: ")
marks = input("Enter % of Marks of Student: ")
rec[name] = marks
print("Name of Student", "\t", "% of Marks")
for name in rec:
print("\t", name, "\t\t", rec[name])
โ๏ธ Updating Dictionary Elements¶
d = {100: "Durga", 200: "Ravi", 300: "Shiva"}
d[400] = "Pavan" # Adds new key
d[100] = "Sunny" # Updates value for key 100
print(d)
โ Deleting Elements from a Dictionary¶
Delete by Key¶
Clear All Entries¶
Delete Entire Dictionary¶
โ๏ธ Dictionary Built-in Functions¶
1. dict()
¶
2. len()
¶
3. clear()
¶
4. get()
¶
5. pop()
¶
6. popitem()
¶
7. keys()
¶
8. values()
¶
9. items()
¶
10. copy()
¶
11. setdefault()
¶
12. update()
¶
๐ก Program: Sum of Dictionary Values¶
Example¶
๐ Program: Count Character Occurrences¶
word = input("Enter any word: ")
d = {}
for char in word:
d[char] = d.get(char, 0) + 1
for k, v in d.items():
print(k, "occurred", v, "times")
๐ Program: Count Vowel Occurrences¶
word = input("Enter any word: ")
vowels = {'a', 'e', 'i', 'o', 'u'}
d = {}
for char in word:
if char in vowels:
d[char] = d.get(char, 0) + 1
for k, v in sorted(d.items()):
print(k, "occurred", v, "times")
๐งโ๐ Program: Student Marks Query System¶
n = int(input("Enter the number of students: "))
d = {}
for _ in range(n):
name = input("Enter Student Name: ")
marks = input("Enter Student Marks: ")
d[name] = marks
while True:
name = input("Enter Student Name to get Marks: ")
marks = d.get(name, -1)
if marks == -1:
print("Student Not Found")
else:
print("The Marks of", name, "are", marks)
option = input("Do you want to find another student marks? [Yes/No]: ")
if option.lower() == "no":
break
print("Thanks for using our application!")
43. Python Program to Count the Number of Each Vowel¶
# Program to count the number of each vowels
# string of vowels
vowels = 'aeiou'
ip_str = 'Hello, have you tried our tutorial section yet?'
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)
# count the vowels
for char in ip_str:
if char in count:
count[char] += 1
print(count)
{'a': 2, 'e': 5, 'i': 3, 'o': 5, 'u': 3}
# Using a list and a dictionary comprehension
# Using dictionary and list comprehension
ip_str = 'Hello, have you tried our tutorial section yet?'
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# count the vowels
count = {x:sum([1 for char in ip_str if char == x]) for x in 'aeiou'}
print(count)
vowels = { "a":0, "e":0, "i":0, "o":0, "u":0 }
s = "ashish Bindru"
for word in s:
if word in vowels:
vowels[word]+=1
vowels
vowels = { "a":0, "e":0, "i":0, "o":0, "u":0 }
s = "ashish Bindru"
vowels = {word:s.count(word) for word in s if word in vowels}
vowels
vowels = { "a":0, "e":0, "i":0, "o":0, "u":0 }
s = "ashish Bindru"
vowels = {word: s.count(word) for word in 'aeiou'}
vowels
w = "ashish Bindru"
s=set(w)
v={'a','e','i','o','u'}
d=s.intersection(v)
print("The different vowel present in",w,"are",d)
s = "ashish Bindru"
v="aeiou"
for w in v:
print(s.count(w))
# print("The different vowel present in",w,"are",d)
48. Python Program to Merge Two Dictionaries¶
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict1.copy()
merged_dict.update(dict2)
print(merged_dict)
53. Python Program to Iterate Over Dictionaries Using for Loop¶
# Example 1: Access both key and value using items()
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key, value in dt.items():
print(key, value)
a juice b grill c corn
# Example 2: Access both key and value without using items()
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key in dt:
print(key, dt[key])
54. Python Program to Sort a Dictionary by Value¶
# Example 1: Sort the dictionary based on values
dt = {5:4, 1:6, 6:3}
sorted_dt = {key: value for key, value in sorted(dt.items(), key=lambda item: item[1])}
print(sorted_dt)
{6: 3, 5: 4, 1: 6}
# Example 2: Sort only the values
dt = {5:4, 1:6, 6:3}
sorted_dt_value = sorted(dt.values())
print(sorted_dt_value)
[3, 4, 6]
59. Python Program to Check if a Key is Already Present in a Dictionary¶
75. Python Program to Convert Two Lists Into a Dictionary¶
The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.
output
{'k': 'a', 'l': 's', 'm': 'h'}
# Example 2: Using list comprehension
index = [1, 2, 3]
languages = ['python', 'c', 'c++']
dictionary = {k: v for k, v in zip(index, languages)}
print(dictionary)
output:
{1: 'python', 2: 'c', 3: 'c++'}