Implementing an Ordered Default Dictionary
An ordered, default dictionary combines the functionality of both OrderedDict and defaultdict from the collections module in Python. To achieve this, you can utilize the DefaultOrderedDict class, as demonstrated below:
<code class="python">from collections import OrderedDict, Callable class DefaultOrderedDict(OrderedDict): def __init__(self, default_factory=None, *a, **kw): if (default_factory is not None and not isinstance(default_factory, Callable)): raise TypeError('first argument must be callable') OrderedDict.__init__(self, *a, **kw) self.default_factory = default_factory def __getitem__(self, key): try: return OrderedDict.__getitem__(self, key) except KeyError: return self.__missing__(key) def __missing__(self, key): if self.default_factory is None: raise KeyError(key) self[key] = value = self.default_factory() return value # ... (remaining implementation omitted for brevity)</code>
This class offers the benefits of both OrderedDict, which maintains the order of key-value pairs, and defaultdict, which provides a default value for non-existent keys. It allows you to access and modify elements while preserving their original order.
The above is the detailed content of How can I create an ordered default dictionary in Python?. For more information, please follow other related articles on the PHP Chinese website!