Bidirectional Mapping Library
The bidict library for Python provides efficient and Pythonic data structures for working with bidirectional (one-to-one) mappings. It offers familiar dictionary-like APIs, automatically keeping forward and inverse mappings in sync. The library is mature, actively maintained, and currently at version 0.23.1, with a regular release cadence. [1, 3, 10]
Warnings
- breaking The `.inv` attribute for accessing the inverse mapping was renamed to `.inverse`. While `.inv` was an alias for a period, it's recommended to use `.inverse` for clarity and future compatibility.
- breaking Support for Python 3.6 was dropped. If you are using bidict with Python 3.6, you must remain on an older version of the library or upgrade your Python interpreter.
- breaking Several old APIs, including the `on_dup_key`, `on_dup_val`, and `on_dup_kv` arguments to `put()` and `putall()`, as well as the constants `bidict.OVERWRITE` and `bidict.IGNORE`, were removed.
- gotcha Unlike standard `dict` values, values stored in a `bidict` must be hashable. This is because values serve as keys in the inverse mapping, and keys must always be hashable in Python dictionaries.
- gotcha For `OrderedBidict`, the `==` operator (`__eq__`) performs an order-insensitive comparison, similar to regular `dict`s. If you require order-sensitive equality checking, use the `equals_order_sensitive()` method.
- gotcha Attempting to create a bidirectional mapping using two separate `dict`s or a single `dict` with duplicated key/value entries is error-prone and leads to manual synchronization issues and potential data inconsistency. `bidict` handles these invariants automatically.
- deprecated The `bidict.__version_info__` attribute was removed.
Install
-
pip install bidict
Imports
- bidict
from bidict import bidict
- bidict.inv
my_bidict.inverse
Quickstart
from bidict import bidict
element_by_symbol = bidict({'H': 'hydrogen'})
print(f"Forward mapping: {element_by_symbol['H']}")
print(f"Inverse mapping: {element_by_symbol.inverse['hydrogen']}")
# Updates are automatically synchronized in both directions
element_by_symbol['H'] = 'hydrogène'
print(f"Updated forward mapping: {element_by_symbol['H']}")
print(f"Updated inverse mapping: {element_by_symbol.inverse['hydrogène']}")