API#

This page contains auto-generated documentation from the bidict source code.

bidict#

The bidirectional mapping library for Python.


bidict by example:

>>> from bidict import bidict
>>> element_by_symbol = bidict({'H': 'hydrogen'})
>>> element_by_symbol['H']
'hydrogen'
>>> element_by_symbol.inverse['hydrogen']
'H'

Please see https://github.com/jab/bidict for the most up-to-date code and https://bidict.readthedocs.io for the most up-to-date documentation if you are reading this elsewhere.


class bidict.BidirectionalMapping#

Bases: Mapping[KT, VT]

Abstract base class for bidirectional mapping types.

Extends collections.abc.Mapping primarily by adding the (abstract) inverse property, which implementers of BidirectionalMapping should override to return a reference to the inverse BidirectionalMapping instance.

__abstractmethods__ = frozenset({'__getitem__', '__iter__', '__len__', 'inverse'})#
__inverted__()[source]#

Get an iterator over the items in inverse.

This is functionally equivalent to iterating over the items in the forward mapping and inverting each one on the fly, but this provides a more efficient implementation: Assuming the already-inverted items are stored in inverse, just return an iterator over them directly.

Providing this default implementation enables external functions, particularly inverted(), to use this optimized implementation when available, instead of having to invert on the fly.

See also bidict.inverted()

Return type:

Iterator[tuple[VT, KT]]

__module__ = 'bidict'#
__orig_bases__ = (typing.Mapping[~KT, ~VT],)#
__parameters__ = (~KT, ~VT)#
__slots__ = ()#
abstract property inverse: BidirectionalMapping[VT, KT]#

The inverse of this bidirectional mapping instance.

See also bidict.BidictBase.inverse, bidict.BidictBase.inv

Raises:

NotImplementedError – Meant to be overridden in subclasses.

class bidict.MutableBidirectionalMapping#

Bases: BidirectionalMapping[KT, VT], MutableMapping[KT, VT]

Abstract base class for mutable bidirectional mapping types.

__abstractmethods__ = frozenset({'__delitem__', '__getitem__', '__iter__', '__len__', '__setitem__', 'inverse'})#
__annotations__ = {}#
__module__ = 'bidict'#
__orig_bases__ = (bidict.BidirectionalMapping[~KT, ~VT], typing.MutableMapping[~KT, ~VT])#
__parameters__ = (~KT, ~VT)#
__slots__ = ()#
class bidict.BidictBase(arg=(), /, **kw)#

Bases: BidirectionalMapping[KT, VT]

Base class implementing BidirectionalMapping.

Parameters:
  • arg (MapOrItems[KT, VT]) –

  • kw (VT) –

__abstractmethods__ = frozenset({})#
__annotations__ = {'__reversed__': 't.ClassVar[t.Any]', '_fwdm': 't.MutableMapping[KT, VT]', '_fwdm_cls': 't.ClassVar[type[t.MutableMapping[t.Any, t.Any]]]', '_inv_cls': 't.ClassVar[type[BidictBase[t.Any, t.Any]]]', '_invm': 't.MutableMapping[VT, KT]', '_invm_cls': 't.ClassVar[type[t.MutableMapping[t.Any, t.Any]]]'}#
__contains__(key)[source]#

True if the mapping contains the specified key, else False.

Parameters:

key (Any) –

Return type:

bool

__copy__()[source]#

Used for the copy protocol. See the copy module.

Parameters:

self (BT) –

Return type:

BT

__dict__ = mappingproxy({'__module__': 'bidict', '__annotations__': {'_fwdm': 't.MutableMapping[KT, VT]', '_invm': 't.MutableMapping[VT, KT]', '_fwdm_cls': 't.ClassVar[type[t.MutableMapping[t.Any, t.Any]]]', '_invm_cls': 't.ClassVar[type[t.MutableMapping[t.Any, t.Any]]]', '_inv_cls': 't.ClassVar[type[BidictBase[t.Any, t.Any]]]', '__reversed__': 't.ClassVar[t.Any]'}, '__doc__': 'Base class implementing :class:`BidirectionalMapping`.', 'on_dup': OnDup(key=OnDupAction.DROP_OLD, val=OnDupAction.RAISE), '_fwdm_cls': <class 'dict'>, '_invm_cls': <class 'dict'>, '__init_subclass__': <classmethod(<function BidictBase.__init_subclass__>)>, '_init_class': <classmethod(<function BidictBase._init_class>)>, '_set_reversed': <classmethod(<function BidictBase._set_reversed>)>, '_ensure_inv_cls': <classmethod(<function BidictBase._ensure_inv_cls>)>, '_make_inv_cls': <classmethod(<function BidictBase._make_inv_cls>)>, '_inv_cls_dict_diff': <classmethod(<function BidictBase._inv_cls_dict_diff>)>, '__init__': <function BidictBase.__init__>, 'inverse': <property object>, '_make_inverse': <function BidictBase._make_inverse>, 'inv': <property object>, '__repr__': <function BidictBase.__repr__>, 'values': <function BidictBase.values>, 'keys': <function BidictBase.keys>, 'items': <function BidictBase.items>, '__contains__': <function BidictBase.__contains__>, '__eq__': <function BidictBase.__eq__>, 'equals_order_sensitive': <function BidictBase.equals_order_sensitive>, '_dedup': <function BidictBase._dedup>, '_write': <function BidictBase._write>, '_update': <function BidictBase._update>, '__copy__': <function BidictBase.__copy__>, 'copy': <function BidictBase.copy>, '_from_other': <staticmethod(<function BidictBase._from_other>)>, '_init_from': <function BidictBase._init_from>, '__or__': <function BidictBase.__or__>, '__ror__': <function BidictBase.__ror__>, '__len__': <function BidictBase.__len__>, '__iter__': <function BidictBase.__iter__>, '__getitem__': <function BidictBase.__getitem__>, '__reduce__': <function BidictBase.__reduce__>, '__orig_bases__': (bidict.BidirectionalMapping[~KT, ~VT],), '__dict__': <attribute '__dict__' of 'BidictBase' objects>, '__weakref__': <attribute '__weakref__' of 'BidictBase' objects>, '__hash__': None, '__parameters__': (~KT, ~VT), '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>, '_inv_cls': <class 'bidict.BidictBase'>, '__reversed__': <function _fwdm_reversed>})#
__eq__(other)[source]#

x.__eq__(other) ⟺ x == other

Equivalent to dict(x.items()) == dict(other.items()) but more efficient.

Note that bidict's __eq__() implementation is inherited by subclasses, in particular by the ordered bidict subclasses, so even with ordered bidicts, == comparison is order-insensitive (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive).

See also equals_order_sensitive()

Parameters:

other (object) –

Return type:

bool

__getitem__(key)[source]#

x.__getitem__(key) ⟺ x[key]

Parameters:

key (KT) –

Return type:

VT

__hash__ = None#
__init__(arg=(), /, **kw)[source]#

Make a new bidirectional mapping. The signature behaves like that of dict. ktems passed via positional arg are processed first, followed by any items passed via keyword argument. Any duplication encountered along the way is handled as per on_dup.

Parameters:
  • arg (Maplike[KT, VT] | Iterable[Tuple[KT, VT]]) –

  • kw (VT) –

Return type:

None

classmethod __init_subclass__()[source]#

Function to initialize subclasses.

Return type:

None

__iter__()[source]#

Iterator over the contained keys.

Return type:

Iterator[KT]

__len__()[source]#

The number of contained items.

Return type:

int

__module__ = 'bidict'#
__or__(other)[source]#

Return self|other.

Parameters:
  • self (BT) –

  • other (Mapping[KT, VT]) –

Return type:

BT

__orig_bases__ = (bidict.BidirectionalMapping[~KT, ~VT],)#
__parameters__ = (~KT, ~VT)#
__reduce__()[source]#

Return state information for pickling.

Return type:

tuple[Any, …]

__repr__()[source]#

See repr().

Return type:

str

__reversed__()#

Iterator over the contained keys in reverse order.

Parameters:

self (BidictBase[KT, Any]) –

Return type:

Iterator[KT]

__ror__(other)[source]#

Return other|self.

Parameters:
  • self (BT) –

  • other (Mapping[KT, VT]) –

Return type:

BT

__weakref__#

list of weak references to the object (if defined)

copy()[source]#

Make a (shallow) copy of this bidict.

Parameters:

self (BT) –

Return type:

BT

equals_order_sensitive(other)[source]#

Order-sensitive equality check.

See also OrderedBidict()'s __eq__() is order-insensitive (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive)

Parameters:

other (object) –

Return type:

bool

property inv: BidictBase[VT, KT]#

Alias for inverse.

property inverse: BidictBase[VT, KT]#

The inverse of this bidirectional mapping instance.

items()[source]#

A set-like object providing a view on the contained items.

When b._fwdm is a dict, b.items() returns a dict_items object that behaves exactly the same as collections.abc.ItemsView(b), except for:

  • offering better performance

  • being reversible on Python 3.8+

  • having a .mapping attribute in Python 3.10+ that exposes a mappingproxy to b._fwdm.

Return type:

ItemsView[KT, VT]

keys()[source]#

A set-like object providing a view on the contained keys.

When b._fwdm is a dict, b.keys() returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b), except for

  • offering better performance

  • being reversible on Python 3.8+

  • having a .mapping attribute in Python 3.10+ that exposes a mappingproxy to b._fwdm.

Return type:

KeysView[KT]

on_dup = (OnDupAction.DROP_OLD, OnDupAction.RAISE)#
values()[source]#

A set-like object providing a view on the contained values.

Since the values of a bidict are equivalent to the keys of its inverse, this method returns a set-like object for this bidict’s values rather than just a collections.abc.ValuesView. This object supports set operations like union and difference, and constant- rather than linear-time containment checks, and is no more expensive to provide than the less capable collections.abc.ValuesView would be.

See keys() for more information.

Return type:

BidictKeysView[VT]

class bidict.BidictKeysView(mapping)#

Bases: KeysView[KT], ValuesView[KT]

Since the keys of a bidict are the values of its inverse (and vice versa), the ValuesView result of calling bi.values() is also a KeysView of bi.inverse.

__abstractmethods__ = frozenset({})#
__annotations__ = {}#
__dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Since the keys of a bidict are the values of its inverse (and vice versa),\n    the :class:`~collections.abc.ValuesView` result of calling *bi.values()*\n    is also a :class:`~collections.abc.KeysView` of *bi.inverse*.\n    ', '__orig_bases__': (typing.KeysView[~KT], typing.ValuesView[~KT]), '__dict__': <attribute '__dict__' of 'BidictKeysView' objects>, '__weakref__': <attribute '__weakref__' of 'BidictKeysView' objects>, '__parameters__': (~KT,), '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>, '__annotations__': {}})#
__module__ = 'bidict'#
__orig_bases__ = (typing.KeysView[~KT], typing.ValuesView[~KT])#
__parameters__ = (~KT,)#
__weakref__#

list of weak references to the object (if defined)

class bidict.GeneratedBidictInverse#

Bases: object

Base class for dynamically-generated inverse bidict classes.

__dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Base class for dynamically-generated inverse bidict classes.', '__dict__': <attribute '__dict__' of 'GeneratedBidictInverse' objects>, '__weakref__': <attribute '__weakref__' of 'GeneratedBidictInverse' objects>, '__annotations__': {}})#
__module__ = 'bidict'#
__weakref__#

list of weak references to the object (if defined)

class bidict.MutableBidict(arg=(), /, **kw)#

Bases: BidictBase[KT, VT], MutableBidirectionalMapping[KT, VT]

Base class for mutable bidirectional mappings.

Parameters:
  • arg (MapOrItems[KT, VT]) –

  • kw (VT) –

__abstractmethods__ = frozenset({})#
__annotations__ = {}#
__delitem__(key)[source]#

x.__delitem__(y) ⟺ del x[y]

Parameters:

key (KT) –

Return type:

None

__ior__(other)[source]#

Return self|=other.

Parameters:

other (Mapping[KT, VT]) –

Return type:

MutableBidict[KT, VT]

__module__ = 'bidict'#
__orig_bases__ = (bidict.BidictBase[~KT, ~VT], bidict.MutableBidirectionalMapping[~KT, ~VT])#
__parameters__ = (~KT, ~VT)#
__reversed__()#

Iterator over the contained keys in reverse order.

Parameters:

self (BidictBase[KT, Any]) –

Return type:

Iterator[KT]

__setitem__(key, val)[source]#

Set the value for key to val.

If key is already associated with val, this is a no-op.

If key is already associated with a different value, the old value will be replaced with val, as with dict’s __setitem__().

If val is already associated with a different key, an exception is raised to protect against accidental removal of the key that’s currently associated with val.

Use put() instead if you want to specify different behavior in the case that the provided key or value duplicates an existing one. Or use forceput() to unconditionally associate key with val, replacing any existing items as necessary to preserve uniqueness.

Raises:
Parameters:
  • key (KT) –

  • val (VT) –

Return type:

None

clear()[source]#

Remove all items.

Return type:

None

forceput(key, val)[source]#

Associate key with val unconditionally.

Replace any existing mappings containing key key or value val as necessary to preserve uniqueness.

Parameters:
  • key (KT) –

  • val (VT) –

Return type:

None

forceupdate(arg=(), /, **kw)[source]#

Like a bulk forceput().

Parameters:
  • arg (Maplike[KT, VT] | Iterable[Tuple[KT, VT]]) –

  • kw (VT) –

Return type:

None

pop(key, default=MissingT.MISSING, /)[source]#

x.pop(k[, d]) → v

Remove specified key and return the corresponding value.

Raises:

KeyError – if key is not found and no default is provided.

Parameters:
  • key (KT) –

  • default (DT | MissingT) –

Return type:

VT | DT

popitem()[source]#

x.popitem() → (k, v)

Remove and return some item as a (key, value) pair.

Raises:

KeyError – if x is empty.

Return type:

tuple[KT, VT]

put(key, val, on_dup=(OnDupAction.RAISE, OnDupAction.RAISE))[source]#

Associate key with val, honoring the OnDup given in on_dup.

For example, if on_dup is ON_DUP_RAISE, then key will be associated with val if and only if key is not already associated with an existing value and val is not already associated with an existing key, otherwise an exception will be raised.

If key is already associated with val, this is a no-op.

Raises:
Parameters:
  • key (KT) –

  • val (VT) –

  • on_dup (OnDup) –

Return type:

None

putall(items, on_dup=(OnDupAction.RAISE, OnDupAction.RAISE))[source]#

Like a bulk put().

If one of the given items causes an exception to be raised, none of the items is inserted.

Parameters:
Return type:

None

update(arg=(), /, **kw)[source]#

Like calling putall() with self.on_dup passed for on_dup.

Parameters:
  • arg (Maplike[KT, VT] | Iterable[Tuple[KT, VT]]) –

  • kw (VT) –

Return type:

None

class bidict.bidict(arg=(), /, **kw)#

Bases: MutableBidict[KT, VT]

The main bidirectional mapping type.

See Introduction and Basic Usage to get started (also available at https://bidict.rtfd.io).

Parameters:
  • arg (MapOrItems[KT, VT]) –

  • kw (VT) –

__abstractmethods__ = frozenset({})#
__annotations__ = {}#
__module__ = 'bidict'#
__orig_bases__ = (bidict.MutableBidict[~KT, ~VT],)#
__parameters__ = (~KT, ~VT)#
__reversed__()#

Iterator over the contained keys in reverse order.

Parameters:

self (BidictBase[KT, Any]) –

Return type:

Iterator[KT]

class bidict.OnDup(key=OnDupAction.DROP_OLD, val=OnDupAction.RAISE)#

Bases: NamedTuple

A combination of OnDupActions specifying how to handle various types of duplication.

The key field specifies what action to take when a duplicate key is encountered.

The val field specifies what action to take when a duplicate value is encountered.

In the case of both key and value duplication across two different items, only val is used.

See also Values Must Be Unique (https://bidict.rtfd.io/basic-usage.html#values-must-be-unique)

Parameters:
__annotations__ = {'key': ForwardRef('OnDupAction'), 'val': ForwardRef('OnDupAction')}#
__getnewargs__()#

Return self as a plain tuple. Used by copy and pickle.

__match_args__ = ('key', 'val')#
__module__ = 'bidict'#
static __new__(_cls, key=OnDupAction.DROP_OLD, val=OnDupAction.RAISE)#

Create new instance of OnDup(key, val)

Parameters:
__orig_bases__ = (<function NamedTuple>,)#
__repr__()#

Return a nicely formatted representation string

__slots__ = ()#
key: OnDupAction#

Alias for field number 0

val: OnDupAction#

Alias for field number 1

class bidict.OnDupAction(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: Enum

An action to take to prevent duplication from occurring.

RAISE = 'RAISE'#
DROP_OLD = 'DROP_OLD'#
DROP_NEW = 'DROP_NEW'#
__module__ = 'bidict'#
exception bidict.BidictException#

Bases: Exception

Base class for bidict exceptions.

__module__ = 'bidict'#
__weakref__#

list of weak references to the object (if defined)

exception bidict.DuplicationError#

Bases: BidictException

Base class for exceptions raised when uniqueness is violated as per the RAISE OnDupAction.

__annotations__ = {}#
__module__ = 'bidict'#
exception bidict.KeyAndValueDuplicationError#

Bases: KeyDuplicationError, ValueDuplicationError

Raised when a given item’s key and value are not unique.

That is, its key duplicates that of another item, and its value duplicates that of a different other item.

__annotations__ = {}#
__module__ = 'bidict'#
exception bidict.KeyDuplicationError#

Bases: DuplicationError

Raised when a given key is not unique.

__annotations__ = {}#
__module__ = 'bidict'#
exception bidict.ValueDuplicationError#

Bases: DuplicationError

Raised when a given value is not unique.

__annotations__ = {}#
__module__ = 'bidict'#
class bidict.frozenbidict(arg=(), /, **kw)#

Bases: BidictBase[KT, VT]

Immutable, hashable bidict type.

Parameters:
  • arg (MapOrItems[KT, VT]) –

  • kw (VT) –

__abstractmethods__ = frozenset({})#
__annotations__ = {'_hash': 'int'}#
__hash__()[source]#

The hash of this bidict as determined by its items.

Return type:

int

__module__ = 'bidict'#
__orig_bases__ = (bidict.BidictBase[~KT, ~VT],)#
__parameters__ = (~KT, ~VT)#
__reversed__()#

Iterator over the contained keys in reverse order.

Parameters:

self (BidictBase[KT, Any]) –

Return type:

Iterator[KT]

bidict.inverted(arg)#

Yield the inverse items of the provided object.

If arg has a callable() __inverted__ attribute, return the result of calling it.

Otherwise, return an iterator over the items in arg, inverting each item on the fly.

See also bidict.BidirectionalMapping.__inverted__

Parameters:

arg (Maplike[KT, VT] | Iterable[Tuple[KT, VT]]) –

Return type:

Iterator[Tuple[VT, KT]]

class bidict.OrderedBidictBase(arg=(), /, **kw)#

Bases: BidictBase[KT, VT]

Base class implementing an ordered BidirectionalMapping.

Parameters:
  • arg (MapOrItems[KT, VT]) –

  • kw (VT) –

__abstractmethods__ = frozenset({})#
__annotations__ = {'_bykey': 'bool', '_node_by_korv': 'bidict[t.Any, Node]'}#
__init__(arg=(), /, **kw)[source]#

Make a new ordered bidirectional mapping. The signature behaves like that of dict. Items passed in are added in the order they are passed, respecting the on_dup class attribute in the process.

The order in which items are inserted is remembered, similar to collections.OrderedDict.

Parameters:
  • arg (Maplike[KT, VT] | Iterable[Tuple[KT, VT]]) –

  • kw (VT) –

Return type:

None

__iter__()[source]#

Iterator over the contained keys in insertion order.

Return type:

Iterator[KT]

__module__ = 'bidict'#
__orig_bases__ = (bidict.BidictBase[~KT, ~VT],)#
__parameters__ = (~KT, ~VT)#
__reversed__()[source]#

Iterator over the contained keys in reverse insertion order.

Return type:

Iterator[KT]

class bidict.OrderedBidict(arg=(), /, **kw)#

Bases: OrderedBidictBase[KT, VT], MutableBidict[KT, VT]

Mutable bidict type that maintains items in insertion order.

Parameters:
  • arg (MapOrItems[KT, VT]) –

  • kw (VT) –

__abstractmethods__ = frozenset({})#
__annotations__ = {}#
__module__ = 'bidict'#
__orig_bases__ = (bidict.OrderedBidictBase[~KT, ~VT], bidict.MutableBidict[~KT, ~VT])#
__parameters__ = (~KT, ~VT)#
clear()[source]#

Remove all items.

Return type:

None

items()[source]#

A set-like object providing a view on the contained items.

Return type:

ItemsView[KT, VT]

keys()[source]#

A set-like object providing a view on the contained keys.

Return type:

KeysView[KT]

move_to_end(key, last=True)[source]#

Move the item with the given key to the end if last is true, else to the beginning.

Raises:

KeyError – if key is missing

Parameters:
  • key (KT) –

  • last (bool) –

Return type:

None

popitem(last=True)[source]#

b.popitem() → (k, v)

If last is true, remove and return the most recently added item as a (key, value) pair. Otherwise, remove and return the least recently added item.

Raises:

KeyError – if b is empty.

Parameters:

last (bool) –

Return type:

tuple[KT, VT]

BidictBase._fwdm_cls: t.ClassVar[type[t.MutableMapping[t.Any, t.Any]]] = <class 'dict'>#
BidictBase._invm_cls: t.ClassVar[type[t.MutableMapping[t.Any, t.Any]]] = <class 'dict'>#
bidict.RAISE = OnDupAction.RAISE#

An action to take to prevent duplication from occurring.

bidict.DROP_OLD = OnDupAction.DROP_OLD#

An action to take to prevent duplication from occurring.

bidict.DROP_NEW = OnDupAction.DROP_NEW#

An action to take to prevent duplication from occurring.

bidict.ON_DUP_DEFAULT = (OnDupAction.DROP_OLD, OnDupAction.RAISE)#

A combination of OnDupActions specifying how to handle various types of duplication.

The key field specifies what action to take when a duplicate key is encountered.

The val field specifies what action to take when a duplicate value is encountered.

In the case of both key and value duplication across two different items, only val is used.

See also Values Must Be Unique (https://bidict.rtfd.io/basic-usage.html#values-must-be-unique)

bidict.ON_DUP_RAISE = (OnDupAction.RAISE, OnDupAction.RAISE)#

A combination of OnDupActions specifying how to handle various types of duplication.

The key field specifies what action to take when a duplicate key is encountered.

The val field specifies what action to take when a duplicate value is encountered.

In the case of both key and value duplication across two different items, only val is used.

See also Values Must Be Unique (https://bidict.rtfd.io/basic-usage.html#values-must-be-unique)

bidict.ON_DUP_DROP_OLD = (OnDupAction.DROP_OLD, OnDupAction.DROP_OLD)#

A combination of OnDupActions specifying how to handle various types of duplication.

The key field specifies what action to take when a duplicate key is encountered.

The val field specifies what action to take when a duplicate value is encountered.

In the case of both key and value duplication across two different items, only val is used.

See also Values Must Be Unique (https://bidict.rtfd.io/basic-usage.html#values-must-be-unique)

bidict.__version__#

The version of bidict represented as a string.