How can I create an ordered dictionary with default values in Python?

Linda Hamilton
Release: 2024-10-28 03:37:30
Original
294 people have browsed it

How can I create an ordered dictionary with default values in Python?

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!