UserList and UserDict in Python Collections module

Filed Under: Python Modules
UserDict & UserList Python

Hello, readers! In this article, we will be focusing on UserList and UserDict in Python Collections module, in detail.

So, let us begin!! 馃檪


Python collections module – Quick Recap!

Before getting into Collections module, let us understand and try to analyze the concept by hovering around the word Collections.

Yes, Collection, let us consider it as a bunch of entities. These entities either represents similar characteristics or different/vivid behavior.

Now, let us relate it to the concepts of Programming.

Python Collections module offers us with various data structure to store and manipulate the data values. By this, it enables us to work around a variety of data values getting them stored according to the feasibility of the data. Every data structure under the tree of Collections module enables us to store similar type or trait of data into it.

Moving ahead, in the context of this topic, we will be focusing on the below data structures offered by Collections module–

  • UserList
  • UserDict

Let us have a look at them in the upcoming sections.


1. Python UserList

As we all know, Python Lists enables us to store similar trait of data with even different data types under a single cover. To customize the already present list, we have Python UserList.

With UserList, we customize the schema of the actual list type and also use the same as an attribute to create classes of type List. So, with UserList, we tend to add a list as an instance that enables us to have user-defined classes to store the data in the list data structure.

By this, we can add new behavior to the existing list object easily and in a customized manner.

Syntax–

collections.UserList(list)

Example 01–

In this example, we have first created and initialized a normal list and then stored the list into the custom UserList format as shown below-

from collections import UserList 
 
lst = [1,2]
  
user_list = UserList(lst) 
print(user_list.data)

Output–

[1, 2]

Example 02–

Having understood the process to store list’s data into a custom UserList, in this example, we have focused on the customization. The UserList module here acts as a wrapper class and for the myinfo list. Further, we inculcate a behavior to the list for the restriction over deletion and that gets down the hierarchy and gets implemented by myinfo list. By this, we can add customized behavior to existing list at runtime using UserList Collection.

from collections import UserList
 
class info(UserList):
     
    def pop(self, s = None):
        raise RuntimeError("Deletion not allowed")
     
myinfo = info([10,20,30])
 
myinfo.append(5)
print("Insertion..")
print(myinfo)
 
myinfo.pop()

Output–

[10, 20, 30, 5]
Traceback (most recent call last):
  File "c:/Users/HP/OneDrive/Desktop/demo.py", line 14, in <module>
    myinfo.pop()
  File "c:/Users/HP/OneDrive/Desktop/demo.py", line 6, in pop      
    raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed

2. Python UserDict

Python Dictionary is a data structure that lets us store data values in relative key-value pairs. But, the data stored here refers to a static/pre-defined format of storage and access values.

With UserDict, we can customize the functioning of the usual Dictionary. It enables us to add functionality and power to the existing Dictionary in terms of the storage structure.

UserDict is a wrapper class that wraps the Dictionary structure around the storage object entities. By this, we tend to add customized behavior to the Dictionary. Also, it takes a dictionary object as input parameter and gets a dictionary structure built in the form of customized class being stored in the dictionary object.

Syntax–

collections.UserDict(data)

Example 01–

Here, we have added an existing dictionary to the UserDict as shown below-

from collections import UserDict 
 
info = {'James':20, 
    'Johan': 21, 
    'Jinny': 32} 
  
user_dict = UserDict(info) 
print(user_dict.data)

Output:

{'James': 20, 'Johan': 21, 'Jinny': 32}

Example 02–

Now, we have added customized behavior to the existing myinfo dictionary.

  • The UserDict acts as a wrapper class around the existing dictionary.
  • It also adds a customized behavior – deletion of elements not allowed” to the UserDict which eventually gets down and implemented by the usual dictionary.
from collections import UserDict
 
class info(UserDict):
     
    def pop(self, s = None):
        raise RuntimeError("Deletion not allowed")
     
myinfo = info({'A':00,
    'B': 10})
 
print(myinfo)
 
#Deleting From Dict
myinfo.pop()

Output:

{'A': 0, 'B': 10}
Traceback (most recent call last):
  File "c:/Users/HP/OneDrive/Desktop/demo.py", line 14, in <module>
    myinfo.pop()
  File "c:/Users/HP/OneDrive/Desktop/demo.py", line 6, in pop
    raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed

Conclusion

By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.

For more such posts related to Python Programming, Stay tuned with us.

Till then, Happy Learning!! 馃檪

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content