Hello, readers! In this article, we will be focusing on UserDict and UserList in Python Collections module. So, let us get started! 🙂
Python collections module – A Quick Brush Up!
Python offers us numerous modules to deal with different forms of data and drive towards automation and sustainability. One such module is the Python Collections module.
The Collections Module offers us a simple way to store similar kinds of data under a single roof. As the name suggests, the collection is a group of entities sharing similar characteristics, the same is the feature offered by the Collections module.
In the course of this article, we will be focusing on the below Collections offered by the module–
- UserDict
- UserList
Let us have a look at each of them in the upcoming section.
Understanding the Python UserDict
As we all know, Python offers us with Dictionary data structure to deal with a key-value form of data. UserDict adds customization to it.
That is, Dictionary helps us create a data structure that holds key-value pairs in a static format. With UserDict, we can add some modified functionality by creating a customized dictionary.
It behaves like a wrapper class around the dictionary objects. By this, we can easily add new behavior to the existing dictionary object.
The UserDict collection accepts the existing dictionary as an argument and triggers a dictionary structure that is stored in the usual dict object.
Have a look at the below syntax!
collections.UserDict(data)
Example:
In the below example, we have created a UserDict using the existing dictionary object. In this case, the dictionary is now available as an attribute to make changes to.
from collections import UserDict
data = {'Pune':100,
'Satara': 28,
'Mumbai': 31}
user_dict = UserDict(data)
print(user_dict.data)
Output:
{'Pune': 100, 'Satara': 28, 'Mumbai': 31}
In the below example, we have displayed the customized use of UserDict for a customized class.
Here, we have created a UserDict wherein it acts an a wrapper class for a customized list ‘mydict’.
Thus, it acts an a wrapper class and let us add attributes to the existing dictionary to the UserDict.
Here, we have added a behavior to the Dictionary that the deletion of the element is restricted to happen.
The UserDict wraps up the default created dictionary into it and inculcates the customized behavior stated in the class.
Example:
from collections import UserDict
class mydata(UserDict):
def pop(self, s = None):
raise RuntimeError("Deletion not allowed")
mydict = mydata({'x':10,
'y': 20})
print(mydict)
#Deliting From Dict
mydict.pop()
Output:
{'x': 10, 'y': 20}
Traceback (most recent call last):
File "c:/Users/HP/OneDrive/Desktop/demo.py", line 15, in <module>
mydict.pop()
File "c:/Users/HP/OneDrive/Desktop/demo.py", line 7, in pop
raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
Understanding the Python UserList
Like UserDict, UserList also offers us a way to customize Lists in Python to be inculcated into classes. Python List stores similar types of data with different data types altogether. UserList helps us customize the list and use them as an attribute to create user-defined classes out of them. Having added the list as an instance, it triggers a list that is kept in the usual list data structure.
Syntax:
collections.UserList(list)
Example:
In this example, we have made use of UserList to store the regular list into it as an argument. Further, we can create customized classes out of it using the UserList collection and attribute as a list.
from collections import UserList
lst = [1,2,3,4,5]
user_list = UserList(lst)
print(user_list.data)
Output:
[1, 2, 3, 4, 5]
In the below example, we have displayed the customized use of UserDict for a customized class.
Here, we have created a UserList wherein it acts an a wrapper class for a customized list ‘mylist’. Thus, it acts an a wrapper class and let us add attributes to the existing dictionary to the UserList. Here, we have added a behavior to the List that the deletion of the element is restricted to happen and we even add/insert value to the list through the UserList as a wrapper class. The UserList wraps up the default created dictionary into it and inculcates the customized behavior stated in the class.
Example:
from collections import UserList
class mydata(UserList):
def pop(self, s = None):
raise RuntimeError("Deletion not allowed")
mylist = mydata([10,20,30])
mylist.append(5)
print("Insertion..")
print(mylist)
mylist.pop()
Output:
After Insertion
[10,20,30,5]
Traceback (most recent call last):
File "c:/Users/HP/OneDrive/Desktop/demo.py", line 20, in <module>
L.pop()
File "c:/Users/HP/OneDrive/Desktop/demo.py", line 7, 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!! 🙂