Skip to content

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?

  1. Hash Value:
    A hash value is a fixed-size integer that uniquely identifies an object, generated by the hash() function.

  2. 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.

  3. 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:
my_dict = {"name": "Alice"}  # 'name' is hashable
  • Numbers (int, float, etc.):
my_dict = {42: "Answer"}  # 42 is hashable
  • Tuples (if all elements are hashable):
my_dict = {(1, 2): "coordinates"}  # (1, 2) is hashable

Unhashable Objects

Objects that are mutable (and hence not hashable) include:

  • Lists:
    Lists are mutable and cannot be used as dictionary keys.
my_dict = {[1, 2]: "List"}  # Raises TypeError: unhashable type: 'list'
  • Sets:
    Like lists, sets are mutable and unhashable.
my_dict = {set([1, 2]): "Set"}  # Raises TypeError

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

  1. A dictionary key must be hashable.
  2. Hashable objects allow Python to store dictionary keys in a hash table for fast lookups.
  3. 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

d = {}
# or
d = dict()

Adding Elements

d[100] = "Durga"
d[200] = "Ravi"
d[300] = "Shiva"
print(d)
# Output: {100: 'Durga', 200: 'Ravi', 300: 'Shiva'}

Creating with Predefined Data

d = {100: 'Durga', 200: 'Ravi', 300: 'Shiva'}

๐Ÿ” Accessing Dictionary Elements

d = {100: 'Durga', 200: 'Ravi', 300: 'Shiva'}
print(d[100])  # Output: Durga
print(d[300])  # Output: Shiva

Handling Missing Keys

# Raises KeyError
print(d[400])

# Use `in` operator (Python 3)
if 400 in d:
    print(d[400])

๐Ÿงช 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

del d[100]

Clear All Entries

d.clear()

Delete Entire Dictionary

del d

โš™๏ธ Dictionary Built-in Functions

1. dict()

d = dict()
d = dict({100: "Durga", 200: "Ravi"})
d = dict([(100, "Durga"), (200, "Shiva")])

2. len()

len(d)

3. clear()

d.clear()

4. get()

d.get(key)                 # Returns value or None
d.get(key, default_value)  # Returns value or default

5. pop()

d.pop(key)  # Removes and returns the value

6. popitem()

d.popitem()  # Removes and returns an arbitrary item

7. keys()

d.keys()

8. values()

d.values()

9. items()

d.items()  # Returns key-value pairs

10. copy()

d2 = d.copy()

11. setdefault()

d.setdefault(key, value)

12. update()

d.update(other_dict)

๐Ÿ’ก Program: Sum of Dictionary Values

d = eval(input("Enter dictionary: "))
s = sum(d.values())
print("Sum = ", s)

Example

Input: {'A': 100, 'B': 200, 'C': 300}
Output: Sum = 600

๐Ÿ” 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, **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)
dict1.update(dict2)
dict1

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

# Using in keyword
my_dict = {1: 'a', 2: 'b', 3: 'c'}

if 2 in my_dict:
    print("present")

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.

keys = ["k","l","m"]
values = ["a", "s", "h","i"]

dict(zip(keys, values))

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++'}