Introduction
In this project, you will learn how to implement an immutable dictionary in Python. An immutable dictionary is a data structure that cannot be modified after it is created, which is useful in certain applications where the data needs to remain unchanged.
👀 Preview
d["Connection"]='kee-alive'
d["Host"]='www.labex.io'
TypeError("'ImmutableDict' objects are immutable")
TypeError("'ImmutableDict' objects are immutable")
d.get("Host")='www.labex.io'
🎯 Tasks
In this project, you will learn:
- How to create an
ImmutableDictclass that inherits from the built-indictclass - How to implement methods in the
ImmutableDictclass to prevent modifications to the dictionary - How to test the
ImmutableDictclass to ensure it behaves as expected
🏆 Achievements
After completing this project, you will be able to:
- Understand the concept of immutable data structures and their use cases
- Implement an immutable dictionary in Python using the
ImmutableDictclass - Prevent modifications to the dictionary by overriding the appropriate methods
- Test the
ImmutableDictclass to ensure it works as expected
Implementing the ImmutableDict Class
In this step, you will learn how to implement the ImmutableDict class in the immutable_dict.py file. Follow the steps below to complete this step:
- Open the
immutable_dict.pyfile located in the/home/labex/projectdirectory. - Create a new class called
ImmutableDictthat inherits from the built-indictclass.
class ImmutableDict(dict):
- Implement the following methods in the
ImmutableDictclass to make the dictionary immutable:
def __setitem__(self, key, value):
raise TypeError("'ImmutableDict' objects are immutable")
def __delitem__(self, key):
raise TypeError("'ImmutableDict' objects are immutable")
def pop(self, key, default=None):
raise TypeError("'ImmutableDict' objects are immutable")
def popitem(self):
raise TypeError("'ImmutableDict' objects are immutable")
def clear(self):
raise TypeError("'ImmutableDict' objects are immutable")
def update(self, *args, **kwargs):
raise TypeError("'ImmutableDict' objects are immutable")
def setdefault(self, key, default=None):
raise TypeError("'ImmutableDict' objects are immutable")
These methods override the corresponding methods in the dict class and raise a TypeError exception whenever an attempt is made to modify the dictionary.
- Save the
immutable_dict.pyfile.
Testing the ImmutableDict Class
In this step, you will test the ImmutableDict class to ensure that it behaves as expected. Follow the steps below to complete this step:
- Open the
immutable_dict.pyfile in the/home/labex/projectdirectory. - Add the following code at the end of the file to test the
ImmutableDictclass:
if __name__ == "__main__":
d = ImmutableDict(Connection="kee-alive", Host="www.labex.io")
print(f'{d["Connection"]=}')
print(f'{d["Host"]=}')
try:
d["Host"] = "test.com"
except TypeError as e:
print(repr(e))
try:
d.pop("Host")
except TypeError as e:
print(repr(e))
print(f'{d.get("Host")=}')
- Save the
immutable_dict.pyfile. - Run the
immutable_dict.pyscript in the terminal:
python3 immutable_dict.py
The output should be:
d["Connection"]='kee-alive'
d["Host"]='www.labex.io'
TypeError("'ImmutableDict' objects are immutable")
TypeError("'ImmutableDict' objects are immutable")
d.get("Host")='www.labex.io'
This output demonstrates that the ImmutableDict class behaves as expected, and any attempts to modify the dictionary will raise a TypeError exception.
Congratulations! You have successfully implemented the ImmutableDict class and tested it. You can now use this class in your Python applications to store immutable data structures.
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



