X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=src%2Fpyutils%2Fcollectionz%2Fbidict.py;h=77d11e08daaecb8dd93b5c6f447f6f101c46a848;hb=993b0992473c12294ed659e52b532e1c8cf9cd1e;hp=000fdb36f47f54929db81124f5001aee7762c18b;hpb=b38920f24d1ac948958480c540bc4b8436186765;p=pyutils.git diff --git a/src/pyutils/collectionz/bidict.py b/src/pyutils/collectionz/bidict.py index 000fdb3..77d11e0 100644 --- a/src/pyutils/collectionz/bidict.py +++ b/src/pyutils/collectionz/bidict.py @@ -2,7 +2,36 @@ # © Copyright 2021-2022, Scott Gasch -"""A bidirectional dictionary.""" +""" +The :class:`pyutils.collectionz.bidict.BiDict` class is a subclass +of :py:class:`dict` that implements a bidirectional dictionary. That +is, it maps each key to a value in constant time and each value back +to the one or more keys it is associated with in constant time. It +does this by simply storing the data twice. + +Sample usage:: + + # Initialize with a normal dict... + third_party_wierdos = BiDict({ + 'prometheus-fastapi-instrumentator': 'prometheus_fastapi_instrumentator', + 'scikit-learn': 'sklearn', + 'antlr4-python3-runtime' : 'antlr4', + 'python-dateutil': 'dateutil', + 'speechrecognition': 'speech_recognition', + 'beautifulsoup4': 'bs4', + 'python-dateutil': 'dateutil', + 'homeassistant-api': 'homeassistant_api', + }) + + # Use in one direction: + x = third_party_wierdos['scikit-learn'] + + # Use in opposite direction: + y = third_party_wierdos.inverse['python_dateutil'] + + # Note: type(y) is List since one value may map back to multiple keys. + +""" class BiDict(dict): @@ -51,3 +80,9 @@ class BiDict(dict): if value in self.inverse and not self.inverse[value]: del self.inverse[value] super().__delitem__(key) + + +if __name__ == '__main__': + import doctest + + doctest.testmod()