Python UserDict
In Python, UserDict is a class in the collections module that provides a wrapper around dictionary objects. It allows creating custom dictionary-like classes by extending UserDict and overriding its methods, making it useful for building specialized dictionaries with additional functionality or behavior.
Syntax
collections.UserDict([initialdata])
Parameters:
initialdata: TheUserDictconstructor can take an optional dictionary or mapping object to initialize the data.
Return value:
Returns a dictionary-like object that can be subclassed to customize behavior.
Example 1: Subclassing UserDict
In this example, a custom class is created by subclassing UserDict and overriding common dictionary methods. This shows how to extend and customize dictionary behavior:
from collections import UserDictclass MyUserDict(UserDict):def __setitem__(self, key, value):print(f"Setting {key} = {value}")super().__setitem__(key, value)def __getitem__(self, key):print(f"Getting {key}")return super().__getitem__(key)d = MyUserDict()d["x"] = 42print(d["x"])
The output is:
Setting x = 42Getting x42
Example 2: Basic Wrapper Usage
In this example, UserDict is used directly to wrap a dictionary. The .data attribute exposes the underlying dictionary object:
from collections import UserDictd = UserDict({"a": 1})d["b"] = 2print(d)print(d.data)
The output is:
UserDict({'a': 1, 'b': 2}){'a': 1, 'b': 2}
Example 3: Logging on Set/Delete
In this example, dictionary modifications are logged by overriding __setitem__ and __delitem__:
from collections import UserDictclass LoggingDict(UserDict):def __setitem__(self, key, value):print(f"SET {key!r} = {value!r}")super().__setitem__(key, value)def __delitem__(self, key):print(f"DEL {key!r}")super().__delitem__(key)d = LoggingDict()d["name"] = "Aris"del d["name"]
The output is:
SET 'name' = 'Aris'DEL 'name'
Example 4: Case-Insensitive Keys
In this example, keys are treated case-insensitively by normalizing them to lowercase before storing or retrieving:
from collections import UserDictclass CaseInsensitiveDict(UserDict):def _key(self, key):return key.lower() if isinstance(key, str) else keydef __setitem__(self, key, value):super().__setitem__(self._key(key), value)def __getitem__(self, key):return super().__getitem__(self._key(key))d = CaseInsensitiveDict()d["Name"] = "Mamta"print(d["name"])print(d["NAME"])
The output is:
MamtaMamta
Codebyte Example: Default-Like Behavior
In this example, a default factory is added, similar to collections.defaultdict(), so missing keys automatically get initialized:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours