Python collections.UserDict

The class UserDict in Python acts as a wrapper around dictionary objects. As we know, the dictionary is used to store a key-value pair. The UserDict adds customization to it. In other words, we can create a customized dictionary. By this, we can easily add new behaviour to the existing dictionary object. The UserDict collections accept the existing dictionary as an argument and trigger a dictionary structure that is stored in the usual dict object.

Syntax :

The signature for the UserDict is as shown below.

collections.UserDict(data)

Python UserDict Examples:

Example 1: In this example, we will create a UserDict using the existing dictionary object. In this case, the dictionary is now available as an attribute.

#Importing UserDict 
from collections import UserDict 
#Initializing
data = {'Delhi':'DL', 'Madhya Pradesh': 'MP','Maharashtra': 'MH'}
 
ud = UserDict(data) 
print(ud.data)

Output

{'Delhi': 'DL', 'Madhya Pradesh': 'MP', 'Maharashtra': 'MH'}

Example 2: In this case, we will create a UserDict wherein it acts an a wrapper class for a customized dictionary object. Thus, it will let us update attributes to the existing dictionary to the UserDict.

#Importing UserDict 
from collections import UserDict
#Defining class  
class info(UserDict):
      
    def changevalue(self, s = None):
        self["A"]=s
      
o = info({'A':00,
    'B': 10})
  
print(o)
  
#changing value in Dict
o.changevalue(400)
print(o)

Output

{'A': 0, 'B': 10}
{'A': 400, 'B': 10}

Example 3: In this case, we will create a UserDict wherein it acts as a wrapper class for a customized dictionary object. Thus, it will let us delete attributes to the existing dictionary to the UserDict.

#Importing UserDict 
from collections import UserDict
#Defining class  
class info(UserDict):
      
    def deletevalue(self, s = None):
        del self["A"]
#Creating object      
o = info({'A':00,
    'B': 10})

print(o)
  
#changing value in Dict
o.deletevalue()
print(o)

Output

{'A': 0, 'B': 10}
{'B': 10}

References

Happy Learning 🙂