How to Implement an Efficient Bidirectional Hash Table in Python?

Patricia Arquette
Release: 2024-10-27 20:57:02
Original
988 people have browsed it

How to Implement an Efficient Bidirectional Hash Table in Python?

Implementing an Efficient Bidirectional Hash Table

A bidirectional hash table allows for both key-to-value and value-to-key lookups. While Python's built-in dict data structure excels at key-to-value lookups, it doesn't offer efficient value-to-key retrievals.

An effective method for implementing a bidirectional hash table is to utilize a class that extends the standard dict. This class, named bidict, maintains an inverse directory that automatically updates with any modifications to the regular dict.

Code Implementation:

<code class="python">class bidict(dict):
    def __init__(self, *args, **kwargs):
        super(bidict, self).__init__(*args, **kwargs)
        self.inverse = {}
        for key, value in self.items():
            self.inverse.setdefault(value, []).append(key) 

    def __setitem__(self, key, value):
        if key in self:
            self.inverse[self[key]].remove(key) 
        super(bidict, self).__setitem__(key, value)
        self.inverse.setdefault(value, []).append(key)        

    def __delitem__(self, key):
        self.inverse.setdefault(self[key], []).remove(key)
        if self[key] in self.inverse and not self.inverse[self[key]]: 
            del self.inverse[self[key]]
        super(bidict, self).__delitem__(key)</code>
Copy after login

Key Features:

  • The inverse directory (bd.inverse) is a dictionary that maps values to a list of keys with that value.
  • The inverse directory automatically updates when the bidict is modified.
  • Unlike some bidict implementations, this class allows multiple keys to have the same value.

Usage Example:

<code class="python">bd = bidict({'a': 1, 'b': 2})  
print(bd)                     # {'a': 1, 'b': 2}                 
print(bd.inverse)             # {1: ['a'], 2: ['b']}
bd['c'] = 1                   # Now two keys have the same value (= 1)
print(bd)                     # {'a': 1, 'c': 1, 'b': 2}
print(bd.inverse)             # {1: ['a', 'c'], 2: ['b']}
del bd['c']
print(bd)                     # {'a': 1, 'b': 2}
print(bd.inverse)             # {1: ['a'], 2: ['b']}
del bd['a']
print(bd)                     # {'b': 2}
print(bd.inverse)             # {2: ['b']}
bd['b'] = 3
print(bd)                     # {'b': 3}
print(bd.inverse)             # {2: [], 3: ['b']}</code>
Copy after login

The above is the detailed content of How to Implement an Efficient Bidirectional Hash Table 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!