Python collections.UserDict



The Python UserDict() is a dictionary present in the collections module. It is a class acts as a wrappers around the dictionary objects. This class is useful when one wants to create a dictionary of their own with some modified functionality or with some new functionality.

It can be considered as adding new behavior to the dictionary. This class takes a dictionary instance as an argument and simulates a dictionary that is kept in a regular dictionary. The dictionary is accessible by the data attribute of this class.

Syntax

Following is the syntax of the Python UserDict()

collection.UserDict([data])

Parameters

It accepts dictionary as a parameter.

Return Value

This class returns <class 'collections.UserDict'> object.

Example

Following is a basic example of the Python Userdict() class −

from collections import UserDict
dic = {'a':1,'b': 2,'c': 3,'d':4}
# Creating an UserDict
userD = UserDict(dic)
print(userD)

Following is the output of the above code −

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Inheriting Userdict

We can inherit the properties of the Userdict() and we can add new functions into the class and can also modify the existing methods.

Example

Here, we have create a class, MyDict and inherited the properties of Userdict class. Modified few methods and can added new methods −

# Python program to demonstrate
# userdict
from collections import UserDict
# Creating a Dictionary where
# deletion is not allowed
class MyDict(UserDict):
	# Function to stop deletion
	# from dictionary
	def __del__(self):
		raise RuntimeError("Deletion not allowed")
		
	# Function to stop pop from 
	# dictionary
	def pop(self, s = None):
		raise RuntimeError("Deletion not allowed")
		
	# Function to stop popitem 
	# from Dictionary
	def popitem(self, s = None):
		raise RuntimeError("Deletion not allowed")
	
# Driver's code
dict = MyDict({'a':1,'b': 2,'c': 3})
print("Original Dictionary :", dict)
dict.pop(1)

Following is the output of the above code −

Original Dictionary : {'a': 1, 'b': 2, 'c': 3}
Traceback (most recent call last):
  File "/home/cg/root/43843/main.py", line 30, in <module>
    dict.pop(1)
  File "/home/cg/root/43843/main.py", line 20, in pop
    raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
Exception ignored in: <function MyDict.__del__ at 0x7f2456043880>
Traceback (most recent call last):
  File "/home/cg/root/43843/main.py", line 15, in __del__
RuntimeError: Deletion not allowed
python_modules.htm
Advertisements