Combining OrderedDict and defaultdict for an Ordered Default Dict
OrderedDict and defaultdict are two powerful data structures from Python's collections module. OrderedDict maintains the order of its elements, while defaultdict provides a default value for missing keys. However, combining these features in a single data structure can be challenging.
Custom Implementation using DefaultOrderedDict
One possible solution is to create a custom class called DefaultOrderedDict that inherits from OrderedDict and adds default value functionality. Here's an implementation inspired by a Stack Overflow answer:
<code class="python">from collections import OrderedDict, Callable class DefaultOrderedDict(OrderedDict): # Source: http://stackoverflow.com/a/6190500/562769 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 # Override __getitem__ to handle missing keys def __getitem__(self, key): try: return OrderedDict.__getitem__(self, key) except KeyError: return self.__missing__(key) # Raise KeyError if no default factory is provided def __missing__(self, key): if self.default_factory is None: raise KeyError(key) self[key] = value = self.default_factory() return value # ... (additional methods and overrides for copy, deepcopy, and repr)</code>
This DefaultOrderedDict class combines the functionality of OrderedDict and defaultdict, allowing ordered access to elements and providing a default value for missing keys.
The above is the detailed content of How can I create an ordered dictionary with default values in Python?. For more information, please follow other related articles on the PHP Chinese website!