Skip to content

Add BidirectionalDict recipe to collections #128001

@nineteendo

Description

@nineteendo

Documentation

Originally suggested by @picnixz's comment, recipe by me:

class BidirectionalDict(UserDict):
    def __init__(self, *args, **kwargs):
        self.inverse_data = {}
        super().__init__(*args, **kwargs)

    def __setitem__(self, key, value):
        if key in self.data:
            if value == (old_value := self.data[key]):
                return

            del self.inverse_data[old_value]

        if value in self.inverse_data:
            raise ValueError("Duplicate value")

        self.data[key] = value
        self.inverse_data[value] = key

    def __delitem__(self, key):
        value = self.data[key]
        del self.data[key]
        del self.inverse_data[value]

    @property
    def inverse(self):
        inverse_bidict = BidirectionalDict()
        inverse_bidict.data = self.inverse_data
        inverse_bidict.inverse_data = self.data
        return inverse_bidict

Metadata

Metadata

Assignees

Labels

docsDocumentation in the Doc dir

Projects

Status

Todo

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions