In Python, dictionaries are not hashable by default because they are mutable. However, you can create a hashable dictionary by using an immutable data structure to represent the dictionary.
One way to create a hashable dictionary is by converting it into a frozenset of its items. Here’s an example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
hashable_dict = frozenset(my_dict.items())
Python hashable dict example
Another approach to creating a hashable dictionary is by using a custom class that encapsulates a dictionary and provides a hash function.
class HashableDict:
def __init__(self, dictionary):
self.dictionary = dictionary
def __hash__(self):
return hash(frozenset(self.dictionary.items()))
my_dict = {'a': 1, 'b': 2, 'c': 3}
hashable_dict = HashableDict(my_dict)
print(hashable_dict)
Output:
In this example, we define the HashableDict
class that takes a dictionary as input and stores it as an attribute. The __hash__()
method is implemented to compute the hash value based on the frozenset of the dictionary’s items. By creating an instance of HashableDict
, you have a hashable dictionary that can be used in hash-based data structures.
Remember that when using a custom hashable dictionary, you need to ensure that the keys and values of the dictionary are themselves hashable for accurate hash computation.
Here’s an example of using the hashabledict
class:
class hashabledict(dict):
def __hash__(self):
return hash(tuple(sorted(self.items())))
# Create hashable dictionaries
dict1 = hashabledict({'a': 1, 'b': 2, 'c': 3})
dict2 = hashabledict({'x': 10, 'y': 20})
# Use hashable dictionaries as keys in another dictionary
data = {
dict1: 'Data 1',
dict2: 'Data 2'
}
# Access data using hashable dictionaries as keys
print(data[dict1]) # Output: Data 1
print(data[dict2]) # Output: Data 2
Do comment if you have any doubts or suggestions on this Python dictionary topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.