UserDict objects in Python Tutorial

The UserDict class is a wrapper for dictionary objects. An instance of a UserDict uses a dictionary as its underpinning data structure which can be accessed via the data attribute.

Since UserDict is a subclass of a dictionary, all of the methods and properties of a normal dictionary are applicable to a UserDict. It’s important to note that since python2.2 you can subclass dict directly. Therefore, the only reason that it’s still available is to retain compatibility with python programs running on version 2.1 or earlier. Therefore, if you’re using python3.0+ then the UserDict class is probably a moot point. With that being said here’s the class details for UserDict:

class collections.UserDict([initialdata])

Below is an example of UserDict in action:

>>> from collections import UserDict
>>> apples = UserDict({'r': 'red', 'g': 'green', 'y': 'yellow'})
{'r': 'red', 'g': 'green', 'y': 'yellow'}

Below is a quick example that showcases how to subclass a dict object, and then test that the subclass inherits the methods and properties of the dict object:

>>> class newdict(dict):
...     """ this is a subclass of dict """

>>> a = newdict()
>>> a.update({'1':1, '2':5, '3': 7})
>>> a
{'1': 1, '2': 5, '3': 7}
>>> for key, value in a.items():
...     print(key, value)
1 1
2 5
3 7
============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.