Home >Backend Development >Python Tutorial >How to Create an Ordered Default Dict in Python?

How to Create an Ordered Default Dict in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 18:28:02568browse

How to Create an Ordered Default Dict in Python?

Implementing an Ordered, Default Dict

The built-in collections module in Python provides both OrderedDict and defaultdict, each offering distinct functionalities. An OrderedDict preserves the insertion order of its elements, while a defaultdict automatically generates default values for missing keys based on a specified factory function.

Combining the Power of Both

Combining the capabilities of both data structures, one can create an ordered, default dict that retains the ordering of its elements and initializes missing keys with default values. This can be achieved by extending the OrderedDict class.

Custom Class: DefaultOrderedDict

The following custom class DefaultOrderedDict inherits from OrderedDict and adds the functionality to handle missing keys:

<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</code>

Usage

This class can be used in the same way as a regular OrderedDict:

<code class="python">ordered_default_dict = DefaultOrderedDict(lambda: 0)
ordered_default_dict['key1'] = 1
ordered_default_dict['key2'] = 2</code>

However, if a key is not present, the default value from the factory function is generated:

<code class="python">print(ordered_default_dict['missing_key'])  # Output: 0</code>

The above is the detailed content of How to Create an Ordered Default Dict in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn