Implementing an Immutable Dictionary

PythonPythonBeginner
Practice Now

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 ImmutableDict class that inherits from the built-in dict class
  • How to implement methods in the ImmutableDict class to prevent modifications to the dictionary
  • How to test the ImmutableDict class 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 ImmutableDict class
  • Prevent modifications to the dictionary by overriding the appropriate methods
  • Test the ImmutableDict class 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:

  1. Open the immutable_dict.py file located in the /home/labex/project directory.
  2. Create a new class called ImmutableDict that inherits from the built-in dict class.
class ImmutableDict(dict):
  1. Implement the following methods in the ImmutableDict class 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.

  1. Save the immutable_dict.py file.

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:

  1. Open the immutable_dict.py file in the /home/labex/project directory.
  2. Add the following code at the end of the file to test the ImmutableDict class:
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")=}')
  1. Save the immutable_dict.py file.
  2. Run the immutable_dict.py script 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.

âœĻ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like