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

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/FunctionsGroup -.-> python/keyword_arguments("`Keyword Arguments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("`Catching Exceptions`") python/ErrorandExceptionHandlingGroup -.-> python/raising_exceptions("`Raising Exceptions`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/keyword_arguments -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/variables_data_types -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/conditional_statements -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/lists -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/tuples -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/sets -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/function_definition -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/default_arguments -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/standard_libraries -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/classes_objects -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/polymorphism -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/encapsulation -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/catching_exceptions -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/raising_exceptions -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/data_collections -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} python/build_in_functions -.-> lab-302737{{"`Implementing an Immutable Dictionary`"}} end

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.

Summary

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

Other Python Tutorials you may like