In this lesson, we have seen advanced containers which modify the functionality of a dictionary such as the defaultdict and OrderedDict. The UserDict container wrapper lets us create our own version of a dictionary. This class contains all of the functionality of a normal dict, except that we can access the dictionary data through the data property. Here’s an example of creating a modified dictionary:

from collections import UserDict # Create a class which inherits from the UserDict class class DisplayDict(UserDict): # A new method to increase the dictionary's functionality def display_info(self): print("Number of Keys: " + str(len(self.keys()))) print("Keys: " + str(list(self.keys()))) print("Number of Values: " + str(len(self.values()))) print("Values: " + str(list(self.values()))) # We can also overwrite a method from the dictionary class def clear(self): print("Deleting all items from the dictionary!") super().clear() disp_dict = DisplayDict({'user': 'Mark', 'device': 'desktop', 'num_visits': 37}) disp_dict.display_info() disp_dict.clear()

As shown in this code example, we can add additional methods and overwrite methods from the UserDictclass. This is the same as inheriting from regular classes in Python.

Now let’s create our own dict class!



Let’s try creating a new dictionary which is able to clear orders which are already processed when the method .clean_orders() is called. Import the UserDict class and create a new class which inherits from it called OrderProcessingDict. The .clean_orders() method should search for any keys called ‘order_status’ and if value is equal to 'complete', remove the entire order from the dictionary.


Now that you have created your own class, try creating an instance of it called process_dict while passing data into the constructor. Afterwards, call the .clean_orders() method to automatically clean the orders inside. You can also print your custom dictionary to see the results.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?