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[bidict._typing.KT, bidict._typing.VT]

Abstract base class (ABC) for bidirectional mapping types.

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

__abstractmethods__ = frozenset({'__getitem__', '__iter__', '__len__', 'inverse'})
__class_getitem__ = <bound method GenericAlias of <class 'bidict.BidirectionalMapping'>>
__contains__(key)
__eq__(other)

Return self==value.

abstract __getitem__(key)
__hash__ = None
classmethod __init_subclass__(*args, **kwargs)

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__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[bidict._typing.VT, bidict._typing.KT]]

abstract __iter__()
abstract __len__()
__module__ = 'bidict'
__orig_bases__ = (typing.Mapping[~KT, ~VT],)
__parameters__ = (~KT, ~VT)
__reversed__ = None
__slots__ = ()
classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

_abc_impl = <_abc._abc_data object>
_is_protocol = False
get(k[, d]) D[k] if k in D, else d.  d defaults to None.
abstract property inverse: bidict.BidirectionalMapping[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidirectional mapping instance.

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

Raises

NotImplementedError – Meant to be overridden in subclasses.

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
values() an object providing a view on D's values
class bidict.MutableBidirectionalMapping

Bases: bidict.BidirectionalMapping[bidict._typing.KT, bidict._typing.VT], MutableMapping[bidict._typing.KT, bidict._typing.VT]

Abstract base class (ABC) for mutable bidirectional mapping types.

__abstractmethods__ = frozenset({'__delitem__', '__getitem__', '__iter__', '__len__', '__setitem__', 'inverse'})
__annotations__ = {}
__class_getitem__ = <bound method GenericAlias of <class 'bidict.MutableBidirectionalMapping'>>
__contains__(key)
abstract __delitem__(key)
__eq__(other)

Return self==value.

abstract __getitem__(key)
__hash__ = None
classmethod __init_subclass__(*args, **kwargs)

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__inverted__()

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[bidict._typing.VT, bidict._typing.KT]]

abstract __iter__()
abstract __len__()
__module__ = 'bidict'
__orig_bases__ = (bidict.BidirectionalMapping[~KT, ~VT], typing.MutableMapping[~KT, ~VT])
__parameters__ = (~KT, ~VT)
__reversed__ = None
abstract __setitem__(key, value)
__slots__ = ()
classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

_abc_impl = <_abc._abc_data object>
_is_protocol = False
clear() None.  Remove all items from D.
get(k[, d]) D[k] if k in D, else d.  d defaults to None.
abstract property inverse: bidict.BidirectionalMapping[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidirectional mapping instance.

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

Raises

NotImplementedError – Meant to be overridden in subclasses.

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
pop(k[, d]) v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
update([E, ]**F) None.  Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() an object providing a view on D's values
class bidict.BidictBase(*args, **kw)

Bases: bidict.BidirectionalMapping[bidict._typing.KT, bidict._typing.VT]

Base class implementing BidirectionalMapping.

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

__abstractmethods__ = frozenset({})
__annotations__ = {'_fwdm_cls': typing.Type[typing.MutableMapping[~KT, ~VT]], '_inv': '_t.Optional[BidictBase[VT, KT]]', '_inv_cls': '_t.Type[BidictBase[VT, KT]]', '_invm_cls': typing.Type[typing.MutableMapping[~VT, ~KT]], '_invweak': '_t.Optional[weakref.ReferenceType[BidictBase[VT, KT]]]', '_repr_delegate': typing.Callable}
__class_getitem__ = <bound method GenericAlias of <class 'bidict.BidictBase'>>
__contains__(key)[source]

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

Parameters

key (Any) –

Return type

bool

__copy__()

A shallow copy.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

__dict__ = mappingproxy({'__module__': 'bidict', '__annotations__': {'_fwdm_cls': typing.Type[typing.MutableMapping[~KT, ~VT]], '_invm_cls': typing.Type[typing.MutableMapping[~VT, ~KT]], '_repr_delegate': typing.Callable, '_inv_cls': '_t.Type[BidictBase[VT, KT]]', '_inv': '_t.Optional[BidictBase[VT, KT]]', '_invweak': '_t.Optional[weakref.ReferenceType[BidictBase[VT, KT]]]'}, '__doc__': 'Base class implementing :class:`BidirectionalMapping`.', 'on_dup': OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>), '_fwdm_cls': <class 'dict'>, '_invm_cls': <class 'dict'>, '_repr_delegate': <class 'dict'>, '__init_subclass__': <classmethod(<function BidictBase.__init_subclass__>)>, '__init__': <function BidictBase.__init__>, '_init_inv': <function BidictBase._init_inv>, '_isinv': <property object>, 'inverse': <property object>, 'inv': <property object>, '__repr__': <function BidictBase.__repr__>, 'keys': <function BidictBase.keys>, 'values': <function BidictBase.values>, 'items': <function BidictBase.items>, '__contains__': <function BidictBase.__contains__>, '__eq__': <function BidictBase.__eq__>, 'equals_order_sensitive': <function BidictBase.equals_order_sensitive>, '_pop': <function BidictBase._pop>, '_put': <function BidictBase._put>, '_dedup_item': <function BidictBase._dedup_item>, '_already_have': <staticmethod(<function BidictBase._already_have>)>, '_write_item': <function BidictBase._write_item>, '_update': <function BidictBase._update>, '_update_no_dup_check': <function BidictBase._update_no_dup_check>, '_update_no_rollback': <function BidictBase._update_no_rollback>, '_update_with_rollback': <function BidictBase._update_with_rollback>, '_undo_write': <function BidictBase._undo_write>, 'copy': <function BidictBase.copy>, '__copy__': <function BidictBase.copy>, '__or__': <function BidictBase.__or__>, '__ror__': <function BidictBase.__ror__>, '__len__': <function BidictBase.__len__>, '__iter__': <function BidictBase.__iter__>, '__getitem__': <function BidictBase.__getitem__>, '__reduce__': <function BidictBase.__reduce__>, '__reversed__': <function BidictBase.__reversed__>, '__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>})
__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.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

Parameters

other (object) –

Return type

bool

__getitem__(key)[source]

x.__getitem__(key) ⟺ x[key]

Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

__hash__ = None
__init__(*args, **kw)[source]

Make a new bidirectional dictionary. 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.

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

classmethod __init_subclass__(**kw)[source]

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__inverted__()

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[bidict._typing.VT, bidict._typing.KT]]

__iter__()[source]

Iterator over the contained keys.

Return type

Iterator[bidict._typing.KT]

__len__()[source]

The number of contained items.

Return type

int

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

Return self|other.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

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

Return state information for pickling (otherwise thwarted by _invweak weakref).

__repr__()[source]

See repr().

Return type

str

__reversed__()[source]

Iterator over the contained keys in reverse order.

Return type

Iterator[bidict._typing.KT]

__ror__(other)[source]

Return other|self.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__slots__ = ()
classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__weakref__

list of weak references to the object (if defined)

_abc_impl = <_abc._abc_data object>
static _already_have(key, val, oldkey, oldval)[source]
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • oldkey (Union[bidict._typing.KT, bidict._typing._NONE]) –

  • oldval (Union[bidict._typing.VT, bidict._typing._NONE]) –

Return type

bool

_dedup_item(key, val, on_dup)[source]

Check key and val for any duplication in self.

Handle any duplication as per the passed in on_dup.

(key, val) already present is construed as a no-op, not a duplication.

If duplication is found and the corresponding OnDupAction is DROP_NEW, return None.

If duplication is found and the corresponding OnDupAction is RAISE, raise the appropriate error.

If duplication is found and the corresponding OnDupAction is DROP_OLD, or if no duplication is found, return the _DedupResult (isdupkey, isdupval, oldkey, oldval).

Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

Optional[bidict._base._DedupResult]

_fwdm_cls

alias of dict

_init_inv()[source]
Return type

None

_invm_cls

alias of dict

_is_protocol = False
property _isinv: bool
_pop(key)[source]
Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

_put(key, val, on_dup)[source]
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

None

_repr_delegate

alias of dict

_undo_write(dedup_result, write_result)[source]
Parameters
  • dedup_result (bidict._base._DedupResult) –

  • write_result (bidict._base._WriteResult) –

Return type

None

_update(init, on_dup, *args, **kw)[source]
Parameters
  • init (bool) –

  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_no_dup_check(other)[source]
Parameters

other (bidict.BidirectionalMapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

None

_update_no_rollback(on_dup, *args, **kw)[source]
Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_with_rollback(on_dup, *args, **kw)[source]

Update, rolling back on failure.

Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_write_item(key, val, dedup_result)[source]
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • dedup_result (bidict._base._DedupResult) –

Return type

bidict._base._WriteResult

copy()[source]

A shallow copy.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

equals_order_sensitive(other)[source]

Order-sensitive equality check.

See also __eq__() is order-insensitive

Parameters

other (object) –

Return type

bool

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
property inv: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

property inverse: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

items()[source]

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

Returns a dict_items object that behaves exactly the same as collections.abc.ItemsView(b), except for being much faster when running on CPython, being reversible, and having a .mapping attribute in Python 3.10+ that exposes a mappingproxy pointing back to the (one-way) forward dictionary that backs this bidict.

Return type

bidict._typing.ItemsView[bidict._typing.KT, bidict._typing.VT]

keys()[source]

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

Returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b), except for being much faster when running on CPython, being reversible, and having a .mapping attribute in Python 3.10+ that exposes a mappingproxy pointing back to the (one-way) forward dictionary that backs this bidict.

Return type

bidict._typing.KeysView[bidict._typing.KT]

on_dup = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<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 KeysView for this bidict’s inverse rather than just a ValuesView for this bidict. The KeysView offers the benefit of supporting set operations (including constant- rather than linear-time containment checks) and is just as cheap to provide as the less capable ValuesView would be.

Returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b.inverse), except for being much faster when running on CPython, being reversible, and having a .mapping attribute in Python 3.10+ that exposes a mappingproxy pointing back to the (one-way) inverse dictionary that backs this bidict.

Return type

bidict._typing.KeysView[bidict._typing.VT]

_inv_cls: _t.Type[BidictBase[VT, KT]]
_inv: _t.Optional[BidictBase[VT, KT]]
_invweak: _t.Optional[weakref.ReferenceType[BidictBase[VT, KT]]]
class bidict.MutableBidict(*args, **kw)

Bases: bidict.BidictBase[bidict._typing.KT, bidict._typing.VT], bidict.MutableBidirectionalMapping[bidict._typing.KT, bidict._typing.VT]

Base class for mutable bidirectional mappings.

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

__abstractmethods__ = frozenset({})
__annotations__ = {}
__class_getitem__ = <bound method GenericAlias of <class 'bidict.MutableBidict'>>
__contains__(key)

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

Parameters

key (Any) –

Return type

bool

__copy__()

A shallow copy.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

__delitem__(key)[source]

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

Parameters

key (bidict._typing.KT) –

Return type

None

__dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Base class for mutable bidirectional mappings.', '__delitem__': <function MutableBidict.__delitem__>, '__setitem__': <function MutableBidict.__setitem__>, 'put': <function MutableBidict.put>, 'forceput': <function MutableBidict.forceput>, 'clear': <function MutableBidict.clear>, 'pop': <function MutableBidict.pop>, 'popitem': <function MutableBidict.popitem>, 'update': <function MutableBidict.update>, 'forceupdate': <function MutableBidict.forceupdate>, '__ior__': <function MutableBidict.__ior__>, 'putall': <function MutableBidict.putall>, '__orig_bases__': (bidict.BidictBase[~KT, ~VT], bidict.MutableBidirectionalMapping[~KT, ~VT]), '__parameters__': (~KT, ~VT), '_inv_cls': <class 'bidict.MutableBidict'>, '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>, '__annotations__': {}})
__eq__(other)

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.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

Parameters

other (object) –

Return type

bool

__getitem__(key)

x.__getitem__(key) ⟺ x[key]

Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

__hash__ = None
__init__(*args, **kw)

Make a new bidirectional dictionary. 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.

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

classmethod __init_subclass__(**kw)

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__inverted__()

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[bidict._typing.VT, bidict._typing.KT]]

__ior__(other)[source]

Return self|=other.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.MutableBidict[bidict._typing.KT, bidict._typing.VT]

__iter__()

Iterator over the contained keys.

Return type

Iterator[bidict._typing.KT]

__len__()

The number of contained items.

Return type

int

__module__ = 'bidict'
__or__(other)

Return self|other.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__orig_bases__ = (bidict.BidictBase[~KT, ~VT], bidict.MutableBidirectionalMapping[~KT, ~VT])
__parameters__ = (~KT, ~VT)
__reduce__()

Return state information for pickling (otherwise thwarted by _invweak weakref).

__repr__()

See repr().

Return type

str

__reversed__()

Iterator over the contained keys in reverse order.

Return type

Iterator[bidict._typing.KT]

__ror__(other)

Return other|self.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__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 (bidict._typing.KT) –

  • val (bidict._typing.VT) –

Return type

None

__slots__ = ()
classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__weakref__

list of weak references to the object (if defined)

_abc_impl = <_abc._abc_data object>
static _already_have(key, val, oldkey, oldval)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • oldkey (Union[bidict._typing.KT, bidict._typing._NONE]) –

  • oldval (Union[bidict._typing.VT, bidict._typing._NONE]) –

Return type

bool

_dedup_item(key, val, on_dup)

Check key and val for any duplication in self.

Handle any duplication as per the passed in on_dup.

(key, val) already present is construed as a no-op, not a duplication.

If duplication is found and the corresponding OnDupAction is DROP_NEW, return None.

If duplication is found and the corresponding OnDupAction is RAISE, raise the appropriate error.

If duplication is found and the corresponding OnDupAction is DROP_OLD, or if no duplication is found, return the _DedupResult (isdupkey, isdupval, oldkey, oldval).

Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

Optional[bidict._base._DedupResult]

_fwdm_cls

alias of dict

_init_inv()
Return type

None

_inv_cls

alias of bidict.MutableBidict

_invm_cls

alias of dict

_is_protocol = False
property _isinv: bool
_pop(key)
Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

_put(key, val, on_dup)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

None

_repr_delegate

alias of dict

_undo_write(dedup_result, write_result)
Parameters
  • dedup_result (bidict._base._DedupResult) –

  • write_result (bidict._base._WriteResult) –

Return type

None

_update(init, on_dup, *args, **kw)
Parameters
  • init (bool) –

  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_no_dup_check(other)
Parameters

other (bidict.BidirectionalMapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

None

_update_no_rollback(on_dup, *args, **kw)
Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_with_rollback(on_dup, *args, **kw)

Update, rolling back on failure.

Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_write_item(key, val, dedup_result)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • dedup_result (bidict._base._DedupResult) –

Return type

bidict._base._WriteResult

clear()[source]

Remove all items.

Return type

None

copy()

A shallow copy.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

equals_order_sensitive(other)

Order-sensitive equality check.

See also __eq__() is order-insensitive

Parameters

other (object) –

Return type

bool

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 (bidict._typing.KT) –

  • val (bidict._typing.VT) –

Return type

None

forceupdate(*args, **kw)[source]

Like a bulk forceput().

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
property inv: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

property inverse: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

items()

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

Returns a dict_items object that behaves exactly the same as collections.abc.ItemsView(b), except for being much faster when running on CPython, being reversible, and having a .mapping attribute in Python 3.10+ that exposes a mappingproxy pointing back to the (one-way) forward dictionary that backs this bidict.

Return type

bidict._typing.ItemsView[bidict._typing.KT, bidict._typing.VT]

keys()

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

Returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b), except for being much faster when running on CPython, being reversible, and having a .mapping attribute in Python 3.10+ that exposes a mappingproxy pointing back to the (one-way) forward dictionary that backs this bidict.

Return type

bidict._typing.KeysView[bidict._typing.KT]

on_dup = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>)
pop(key, default=<_NONE>)[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 (bidict._typing.KT) –

  • default (Union[bidict._typing.VT, bidict._typing.DT]) –

Return type

Union[bidict._typing.VT, bidict._typing.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[bidict._typing.KT, bidict._typing.VT]

put(key, val, on_dup=OnDup(key=<RAISE>, val=<RAISE>, kv=<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 (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

None

putall(items, on_dup=OnDup(key=<RAISE>, val=<RAISE>, kv=<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
  • items (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • on_dup (bidict.OnDup) –

Return type

None

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
update(*args, **kw)[source]

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

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

values()

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 KeysView for this bidict’s inverse rather than just a ValuesView for this bidict. The KeysView offers the benefit of supporting set operations (including constant- rather than linear-time containment checks) and is just as cheap to provide as the less capable ValuesView would be.

Returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b.inverse), except for being much faster when running on CPython, being reversible, and having a .mapping attribute in Python 3.10+ that exposes a mappingproxy pointing back to the (one-way) inverse dictionary that backs this bidict.

Return type

bidict._typing.KeysView[bidict._typing.VT]

class bidict.bidict(*args, **kw)

Bases: bidict.MutableBidict[bidict._typing.KT, bidict._typing.VT]

Base class for mutable bidirectional mappings.

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

__abstractmethods__ = frozenset({})
__annotations__ = {}
__class_getitem__ = <bound method GenericAlias of <class 'bidict.bidict'>>
__contains__(key)

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

Parameters

key (Any) –

Return type

bool

__copy__()

A shallow copy.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

__delitem__(key)

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

Parameters

key (bidict._typing.KT) –

Return type

None

__dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Base class for mutable bidirectional mappings.', '__orig_bases__': (bidict.MutableBidict[~KT, ~VT],), '__parameters__': (~KT, ~VT), '_inv_cls': <class 'bidict.bidict'>, '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>, '__annotations__': {}})
__eq__(other)

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.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

Parameters

other (object) –

Return type

bool

__getitem__(key)

x.__getitem__(key) ⟺ x[key]

Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

__hash__ = None
__init__(*args, **kw)

Make a new bidirectional dictionary. 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.

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

classmethod __init_subclass__(**kw)

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__inverted__()

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[bidict._typing.VT, bidict._typing.KT]]

__ior__(other)

Return self|=other.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.MutableBidict[bidict._typing.KT, bidict._typing.VT]

__iter__()

Iterator over the contained keys.

Return type

Iterator[bidict._typing.KT]

__len__()

The number of contained items.

Return type

int

__module__ = 'bidict'
__or__(other)

Return self|other.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__orig_bases__ = (bidict.MutableBidict[~KT, ~VT],)
__parameters__ = (~KT, ~VT)
__reduce__()

Return state information for pickling (otherwise thwarted by _invweak weakref).

__repr__()

See repr().

Return type

str

__reversed__()

Iterator over the contained keys in reverse order.

Return type

Iterator[bidict._typing.KT]

__ror__(other)

Return other|self.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__setitem__(key, val)

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 (bidict._typing.KT) –

  • val (bidict._typing.VT) –

Return type

None

__slots__ = ()
classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__weakref__

list of weak references to the object (if defined)

_abc_impl = <_abc._abc_data object>
static _already_have(key, val, oldkey, oldval)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • oldkey (Union[bidict._typing.KT, bidict._typing._NONE]) –

  • oldval (Union[bidict._typing.VT, bidict._typing._NONE]) –

Return type

bool

_dedup_item(key, val, on_dup)

Check key and val for any duplication in self.

Handle any duplication as per the passed in on_dup.

(key, val) already present is construed as a no-op, not a duplication.

If duplication is found and the corresponding OnDupAction is DROP_NEW, return None.

If duplication is found and the corresponding OnDupAction is RAISE, raise the appropriate error.

If duplication is found and the corresponding OnDupAction is DROP_OLD, or if no duplication is found, return the _DedupResult (isdupkey, isdupval, oldkey, oldval).

Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

Optional[bidict._base._DedupResult]

_fwdm_cls

alias of dict

_init_inv()
Return type

None

_inv_cls

alias of bidict.bidict

_invm_cls

alias of dict

_is_protocol = False
property _isinv: bool
_pop(key)
Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

_put(key, val, on_dup)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

None

_repr_delegate

alias of dict

_undo_write(dedup_result, write_result)
Parameters
  • dedup_result (bidict._base._DedupResult) –

  • write_result (bidict._base._WriteResult) –

Return type

None

_update(init, on_dup, *args, **kw)
Parameters
  • init (bool) –

  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_no_dup_check(other)
Parameters

other (bidict.BidirectionalMapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

None

_update_no_rollback(on_dup, *args, **kw)
Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_with_rollback(on_dup, *args, **kw)

Update, rolling back on failure.

Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_write_item(key, val, dedup_result)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • dedup_result (bidict._base._DedupResult) –

Return type

bidict._base._WriteResult

clear()

Remove all items.

Return type

None

copy()

A shallow copy.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

equals_order_sensitive(other)

Order-sensitive equality check.

See also __eq__() is order-insensitive

Parameters

other (object) –

Return type

bool

forceput(key, val)

Associate key with val unconditionally.

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

Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

Return type

None

forceupdate(*args, **kw)

Like a bulk forceput().

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
property inv: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

property inverse: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

items()

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

Returns a dict_items object that behaves exactly the same as collections.abc.ItemsView(b), except for being much faster when running on CPython, being reversible, and having a .mapping attribute in Python 3.10+ that exposes a mappingproxy pointing back to the (one-way) forward dictionary that backs this bidict.

Return type

bidict._typing.ItemsView[bidict._typing.KT, bidict._typing.VT]

keys()

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

Returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b), except for being much faster when running on CPython, being reversible, and having a .mapping attribute in Python 3.10+ that exposes a mappingproxy pointing back to the (one-way) forward dictionary that backs this bidict.

Return type

bidict._typing.KeysView[bidict._typing.KT]

on_dup = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>)
pop(key, default=<_NONE>)

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 (bidict._typing.KT) –

  • default (Union[bidict._typing.VT, bidict._typing.DT]) –

Return type

Union[bidict._typing.VT, bidict._typing.DT]

popitem()

x.popitem() → (k, v)

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

Raises

KeyError – if x is empty.

Return type

Tuple[bidict._typing.KT, bidict._typing.VT]

put(key, val, on_dup=OnDup(key=<RAISE>, val=<RAISE>, kv=<RAISE>))

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 (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

None

putall(items, on_dup=OnDup(key=<RAISE>, val=<RAISE>, kv=<RAISE>))

Like a bulk put().

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

Parameters
  • items (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • on_dup (bidict.OnDup) –

Return type

None

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
update(*args, **kw)

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

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

values()

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 KeysView for this bidict’s inverse rather than just a ValuesView for this bidict. The KeysView offers the benefit of supporting set operations (including constant- rather than linear-time containment checks) and is just as cheap to provide as the less capable ValuesView would be.

Returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b.inverse), except for being much faster when running on CPython, being reversible, and having a .mapping attribute in Python 3.10+ that exposes a mappingproxy pointing back to the (one-way) inverse dictionary that backs this bidict.

Return type

bidict._typing.KeysView[bidict._typing.VT]

class bidict.frozenbidict(*args, **kw)

Bases: bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

Immutable, hashable bidict type.

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

__abstractmethods__ = frozenset({})
__annotations__ = {'_hash': <class 'int'>}
__class_getitem__ = <bound method GenericAlias of <class 'bidict.frozenbidict'>>
__contains__(key)

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

Parameters

key (Any) –

Return type

bool

__copy__()

A shallow copy.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

__dict__ = mappingproxy({'__module__': 'bidict', '__annotations__': {'_hash': <class 'int'>}, '__doc__': 'Immutable, hashable bidict type.', '__hash__': <function frozenbidict.__hash__>, '__orig_bases__': (bidict.BidictBase[~KT, ~VT],), '__parameters__': (~KT, ~VT), '_inv_cls': <class 'bidict.frozenbidict'>, '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>})
__eq__(other)

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.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

Parameters

other (object) –

Return type

bool

__getitem__(key)

x.__getitem__(key) ⟺ x[key]

Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

__hash__()[source]

The hash of this bidict as determined by its items.

Return type

int

__init__(*args, **kw)

Make a new bidirectional dictionary. 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.

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

classmethod __init_subclass__(**kw)

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__inverted__()

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[bidict._typing.VT, bidict._typing.KT]]

__iter__()

Iterator over the contained keys.

Return type

Iterator[bidict._typing.KT]

__len__()

The number of contained items.

Return type

int

__module__ = 'bidict'
__or__(other)

Return self|other.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__orig_bases__ = (bidict.BidictBase[~KT, ~VT],)
__parameters__ = (~KT, ~VT)
__reduce__()

Return state information for pickling (otherwise thwarted by _invweak weakref).

__repr__()

See repr().

Return type

str

__reversed__()

Iterator over the contained keys in reverse order.

Return type

Iterator[bidict._typing.KT]

__ror__(other)

Return other|self.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__slots__ = ()
classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__weakref__

list of weak references to the object (if defined)

_abc_impl = <_abc._abc_data object>
static _already_have(key, val, oldkey, oldval)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • oldkey (Union[bidict._typing.KT, bidict._typing._NONE]) –

  • oldval (Union[bidict._typing.VT, bidict._typing._NONE]) –

Return type

bool

_dedup_item(key, val, on_dup)

Check key and val for any duplication in self.

Handle any duplication as per the passed in on_dup.

(key, val) already present is construed as a no-op, not a duplication.

If duplication is found and the corresponding OnDupAction is DROP_NEW, return None.

If duplication is found and the corresponding OnDupAction is RAISE, raise the appropriate error.

If duplication is found and the corresponding OnDupAction is DROP_OLD, or if no duplication is found, return the _DedupResult (isdupkey, isdupval, oldkey, oldval).

Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

Optional[bidict._base._DedupResult]

_fwdm_cls

alias of dict

_init_inv()
Return type

None

_inv_cls

alias of bidict.frozenbidict

_invm_cls

alias of dict

_is_protocol = False
property _isinv: bool
_pop(key)
Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

_put(key, val, on_dup)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

None

_repr_delegate

alias of dict

_undo_write(dedup_result, write_result)
Parameters
  • dedup_result (bidict._base._DedupResult) –

  • write_result (bidict._base._WriteResult) –

Return type

None

_update(init, on_dup, *args, **kw)
Parameters
  • init (bool) –

  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_no_dup_check(other)
Parameters

other (bidict.BidirectionalMapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

None

_update_no_rollback(on_dup, *args, **kw)
Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_with_rollback(on_dup, *args, **kw)

Update, rolling back on failure.

Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_write_item(key, val, dedup_result)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • dedup_result (bidict._base._DedupResult) –

Return type

bidict._base._WriteResult

copy()

A shallow copy.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

equals_order_sensitive(other)

Order-sensitive equality check.

See also __eq__() is order-insensitive

Parameters

other (object) –

Return type

bool

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
property inv: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

property inverse: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

items()

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

Returns a dict_items object that behaves exactly the same as collections.abc.ItemsView(b), except for being much faster when running on CPython, being reversible, and having a .mapping attribute in Python 3.10+ that exposes a mappingproxy pointing back to the (one-way) forward dictionary that backs this bidict.

Return type

bidict._typing.ItemsView[bidict._typing.KT, bidict._typing.VT]

keys()

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

Returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b), except for being much faster when running on CPython, being reversible, and having a .mapping attribute in Python 3.10+ that exposes a mappingproxy pointing back to the (one-way) forward dictionary that backs this bidict.

Return type

bidict._typing.KeysView[bidict._typing.KT]

on_dup = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>)
values()

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 KeysView for this bidict’s inverse rather than just a ValuesView for this bidict. The KeysView offers the benefit of supporting set operations (including constant- rather than linear-time containment checks) and is just as cheap to provide as the less capable ValuesView would be.

Returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b.inverse), except for being much faster when running on CPython, being reversible, and having a .mapping attribute in Python 3.10+ that exposes a mappingproxy pointing back to the (one-way) inverse dictionary that backs this bidict.

Return type

bidict._typing.KeysView[bidict._typing.VT]

_hash: int
class bidict.FrozenOrderedBidict(*args, **kw)

Bases: bidict.OrderedBidictBase[bidict._typing.KT, bidict._typing.VT]

Hashable, immutable, ordered bidict type.

Like a hashable bidict.OrderedBidict without the mutating APIs, or like a reversible bidict.frozenbidict even on Python < 3.8. (All bidicts are order-preserving when never mutated, so frozenbidict is already order-preserving, but only on Python 3.8+, where dicts are reversible, are all bidicts (including frozenbidict) also reversible.)

If you are using Python 3.8+, frozenbidict gives you everything that FrozenOrderedBidict gives you, but with less space overhead.

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

__abstractmethods__ = frozenset({})
__annotations__ = {}
__class_getitem__ = <bound method GenericAlias of <class 'bidict.FrozenOrderedBidict'>>
__contains__(key)

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

Parameters

key (Any) –

Return type

bool

__copy__()

A shallow copy of this ordered bidict.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

__dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Hashable, immutable, ordered bidict type.\n\n    Like a hashable :class:`bidict.OrderedBidict`\n    without the mutating APIs, or like a\n    reversible :class:`bidict.frozenbidict` even on Python < 3.8.\n    (All bidicts are order-preserving when never mutated, so frozenbidict is\n    already order-preserving, but only on Python 3.8+, where dicts are\n    reversible, are all bidicts (including frozenbidict) also reversible.)\n\n    If you are using Python 3.8+, frozenbidict gives you everything that\n    FrozenOrderedBidict gives you, but with less space overhead.\n    ', '__hash__': <function frozenbidict.__hash__>, 'keys': <function FrozenOrderedBidict.keys>, 'values': <function FrozenOrderedBidict.values>, '_iter': <function FrozenOrderedBidict._iter>, '__orig_bases__': (bidict.OrderedBidictBase[~KT, ~VT],), '__parameters__': (~KT, ~VT), '_inv_cls': <class 'bidict.FrozenOrderedBidict'>, '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>, '__annotations__': {}})
__eq__(other)

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.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

Parameters

other (object) –

Return type

bool

__getitem__(key)

x.__getitem__(key) ⟺ x[key]

Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

__hash__()

The hash of this bidict as determined by its items.

Return type

int

__init__(*args, **kw)

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
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

classmethod __init_subclass__(**kw)

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__inverted__()

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[bidict._typing.VT, bidict._typing.KT]]

__iter__()

Iterator over the contained keys in insertion order.

Return type

Iterator[bidict._typing.KT]

__len__()

The number of contained items.

Return type

int

__module__ = 'bidict'
__or__(other)

Return self|other.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__orig_bases__ = (bidict.OrderedBidictBase[~KT, ~VT],)
__parameters__ = (~KT, ~VT)
__reduce__()

Return state information for pickling (otherwise thwarted by _invweak weakref).

__repr__()

See repr().

Return type

str

__reversed__()

Iterator over the contained keys in reverse insertion order.

Return type

Iterator[bidict._typing.KT]

__ror__(other)

Return other|self.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__slots__ = ()
classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__weakref__

list of weak references to the object (if defined)

_abc_impl = <_abc._abc_data object>
static _already_have(key, val, nodeinv, nodefwd)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • nodeinv (bidict._orderedbase._Node) –

  • nodefwd (bidict._orderedbase._Node) –

Return type

bool

_dedup_item(key, val, on_dup)

Check key and val for any duplication in self.

Handle any duplication as per the passed in on_dup.

(key, val) already present is construed as a no-op, not a duplication.

If duplication is found and the corresponding OnDupAction is DROP_NEW, return None.

If duplication is found and the corresponding OnDupAction is RAISE, raise the appropriate error.

If duplication is found and the corresponding OnDupAction is DROP_OLD, or if no duplication is found, return the _DedupResult (isdupkey, isdupval, oldkey, oldval).

Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

Optional[bidict._base._DedupResult]

_fwdm_cls

alias of bidict.bidict

_init_inv()
Return type

None

_inv_cls

alias of bidict.FrozenOrderedBidict

_invm_cls

alias of bidict.bidict

_is_protocol = False
property _isinv: bool
_iter(*, reverse=False)[source]
Parameters

reverse (bool) –

Return type

Iterator[bidict._typing.KT]

_pop(key)
Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

_put(key, val, on_dup)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

None

_repr_delegate

alias of list

_undo_write(dedup_result, write_result)
Parameters
  • dedup_result (bidict._base._DedupResult) –

  • write_result (bidict._base._WriteResult) –

Return type

None

_update(init, on_dup, *args, **kw)
Parameters
  • init (bool) –

  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_no_dup_check(other)
Parameters

other (bidict.BidirectionalMapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

None

_update_no_rollback(on_dup, *args, **kw)
Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_with_rollback(on_dup, *args, **kw)

Update, rolling back on failure.

Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_write_item(key, val, dedup_result)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • dedup_result (bidict._base._DedupResult) –

Return type

bidict._base._WriteResult

copy()

A shallow copy of this ordered bidict.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

equals_order_sensitive(other)

Order-sensitive equality check.

See also __eq__() is order-insensitive

Parameters

other (object) –

Return type

bool

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
property inv: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

property inverse: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

items()

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

Return type

bidict._typing.ItemsView[bidict._typing.KT, bidict._typing.VT]

keys()[source]

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

See bidict.BidictBase.keys() for more info.

Return type

bidict._typing.KeysView[bidict._typing.KT]

on_dup = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>)
values()[source]

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

See bidict.BidictBase.values() for more info.

Return type

bidict._typing.KeysView[bidict._typing.VT]

bidict.namedbidict(typename, keyname, valname, *, base_type=<class 'bidict.bidict'>)

Create a new subclass of base_type with custom accessors.

Like collections.namedtuple() for bidicts.

The new class’s __name__ and __qualname__ will be set to typename, and its __module__ will be set to the caller’s module.

Instances of the new class will provide access to their inverse instances via the custom keyname_for property, and access to themselves via the custom valname_for property.

See also the namedbidict usage documentation

Raises
  • ValueError – if any of the typename, keyname, or valname strings is not a valid Python identifier, or if keyname == valname.

  • TypeError – if base_type is not a BidirectionalMapping subclass that provides an _isinv attribute. (Any BidictBase subclass can be passed in, including all the concrete bidict types pictured in the Bidict Types Diagram.

Parameters
Return type

Type[bidict.BidirectionalMapping[bidict._typing.KT, bidict._typing.VT]]

class bidict.OrderedBidictBase(*args, **kw)

Bases: bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

Base class implementing an ordered BidirectionalMapping.

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

__abstractmethods__ = frozenset({})
__annotations__ = {'_fwdm': bidict.bidict[~KT, bidict._orderedbase._Node], '_fwdm_cls': typing.Type[bidict.MutableBidirectionalMapping[~KT, bidict._orderedbase._Node]], '_invm': bidict.bidict[~VT, bidict._orderedbase._Node], '_invm_cls': typing.Type[bidict.MutableBidirectionalMapping[~VT, bidict._orderedbase._Node]]}
__class_getitem__ = <bound method GenericAlias of <class 'bidict.OrderedBidictBase'>>
__contains__(key)

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

Parameters

key (Any) –

Return type

bool

__copy__()

A shallow copy of this ordered bidict.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

__dict__ = mappingproxy({'__module__': 'bidict', '__annotations__': {'_fwdm_cls': typing.Type[bidict.MutableBidirectionalMapping[~KT, bidict._orderedbase._Node]], '_invm_cls': typing.Type[bidict.MutableBidirectionalMapping[~VT, bidict._orderedbase._Node]], '_fwdm': bidict.bidict[~KT, bidict._orderedbase._Node], '_invm': bidict.bidict[~VT, bidict._orderedbase._Node]}, '__doc__': 'Base class implementing an ordered :class:`BidirectionalMapping`.', '_fwdm_cls': <class 'bidict.bidict'>, '_invm_cls': <class 'bidict.bidict'>, '_repr_delegate': <class 'list'>, '__init__': <function OrderedBidictBase.__init__>, '_init_inv': <function OrderedBidictBase._init_inv>, 'copy': <function OrderedBidictBase.copy>, '__copy__': <function OrderedBidictBase.copy>, '__getitem__': <function OrderedBidictBase.__getitem__>, '_pop': <function OrderedBidictBase._pop>, '_already_have': <staticmethod(<function OrderedBidictBase._already_have>)>, '_write_item': <function OrderedBidictBase._write_item>, '_undo_write': <function OrderedBidictBase._undo_write>, '__iter__': <function OrderedBidictBase.__iter__>, '_iter': <function OrderedBidictBase._iter>, '__reversed__': <function OrderedBidictBase.__reversed__>, 'keys': <function OrderedBidictBase.keys>, 'values': <function OrderedBidictBase.values>, 'items': <function OrderedBidictBase.items>, '__orig_bases__': (bidict.BidictBase[~KT, ~VT],), '__parameters__': (~KT, ~VT), '_inv_cls': <class 'bidict.OrderedBidictBase'>, '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>})
__eq__(other)

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.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

Parameters

other (object) –

Return type

bool

__getitem__(key)[source]

x.__getitem__(key) ⟺ x[key]

Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

__hash__ = None
__init__(*args, **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
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

classmethod __init_subclass__(**kw)

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__inverted__()

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[bidict._typing.VT, bidict._typing.KT]]

__iter__()[source]

Iterator over the contained keys in insertion order.

Return type

Iterator[bidict._typing.KT]

__len__()

The number of contained items.

Return type

int

__module__ = 'bidict'
__or__(other)

Return self|other.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__orig_bases__ = (bidict.BidictBase[~KT, ~VT],)
__parameters__ = (~KT, ~VT)
__reduce__()

Return state information for pickling (otherwise thwarted by _invweak weakref).

__repr__()

See repr().

Return type

str

__reversed__()[source]

Iterator over the contained keys in reverse insertion order.

Return type

Iterator[bidict._typing.KT]

__ror__(other)

Return other|self.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__slots__ = ()
classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__weakref__

list of weak references to the object (if defined)

_abc_impl = <_abc._abc_data object>
static _already_have(key, val, nodeinv, nodefwd)[source]
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • nodeinv (bidict._orderedbase._Node) –

  • nodefwd (bidict._orderedbase._Node) –

Return type

bool

_dedup_item(key, val, on_dup)

Check key and val for any duplication in self.

Handle any duplication as per the passed in on_dup.

(key, val) already present is construed as a no-op, not a duplication.

If duplication is found and the corresponding OnDupAction is DROP_NEW, return None.

If duplication is found and the corresponding OnDupAction is RAISE, raise the appropriate error.

If duplication is found and the corresponding OnDupAction is DROP_OLD, or if no duplication is found, return the _DedupResult (isdupkey, isdupval, oldkey, oldval).

Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

Optional[bidict._base._DedupResult]

_fwdm_cls

alias of bidict.bidict

_init_inv()[source]
Return type

None

_inv_cls

alias of bidict.OrderedBidictBase

_invm_cls

alias of bidict.bidict

_is_protocol = False
property _isinv: bool
_iter(*, reverse=False)[source]
Parameters

reverse (bool) –

Return type

Iterator[bidict._typing.KT]

_pop(key)[source]
Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

_put(key, val, on_dup)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

None

_repr_delegate

alias of list

_undo_write(dedup_result, write_result)[source]
Parameters
  • dedup_result (bidict._base._DedupResult) –

  • write_result (bidict._base._WriteResult) –

Return type

None

_update(init, on_dup, *args, **kw)
Parameters
  • init (bool) –

  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_no_dup_check(other)
Parameters

other (bidict.BidirectionalMapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

None

_update_no_rollback(on_dup, *args, **kw)
Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_with_rollback(on_dup, *args, **kw)

Update, rolling back on failure.

Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_write_item(key, val, dedup_result)[source]
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • dedup_result (bidict._base._DedupResult) –

Return type

bidict._base._WriteResult

copy()[source]

A shallow copy of this ordered bidict.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

equals_order_sensitive(other)

Order-sensitive equality check.

See also __eq__() is order-insensitive

Parameters

other (object) –

Return type

bool

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
property inv: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

property inverse: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

items()[source]

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

Return type

bidict._typing.ItemsView[bidict._typing.KT, bidict._typing.VT]

keys()[source]

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

Return type

bidict._typing.KeysView[bidict._typing.KT]

on_dup = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>)
values()[source]

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

Since the values of a bidict are equivalent to the keys of its inverse, this method returns a KeysView for this bidict’s inverse rather than just a ValuesView for this bidict. The KeysView offers the benefit of supporting set operations (including constant- rather than linear-time containment checks) and is just as cheap to provide as the less capable ValuesView would be.

Return type

bidict._typing.KeysView[bidict._typing.VT]

_fwdm: bidict.bidict[bidict._typing.KT, bidict._orderedbase._Node]
_invm: bidict.bidict[bidict._typing.VT, bidict._orderedbase._Node]
class bidict.OrderedBidict(*args, **kw)

Bases: bidict.OrderedBidictBase[bidict._typing.KT, bidict._typing.VT], bidict.MutableBidict[bidict._typing.KT, bidict._typing.VT]

Mutable bidict type that maintains items in insertion order.

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

__abstractmethods__ = frozenset({})
__annotations__ = {}
__class_getitem__ = <bound method GenericAlias of <class 'bidict.OrderedBidict'>>
__contains__(key)

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

Parameters

key (Any) –

Return type

bool

__copy__()

A shallow copy of this ordered bidict.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

__delitem__(key)

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

Parameters

key (bidict._typing.KT) –

Return type

None

__dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Mutable bidict type that maintains items in insertion order.', 'clear': <function OrderedBidict.clear>, 'popitem': <function OrderedBidict.popitem>, 'move_to_end': <function OrderedBidict.move_to_end>, '__orig_bases__': (bidict.OrderedBidictBase[~KT, ~VT], bidict.MutableBidict[~KT, ~VT]), '__parameters__': (~KT, ~VT), '_inv_cls': <class 'bidict.OrderedBidict'>, '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>, '__annotations__': {}})
__eq__(other)

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.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

Parameters

other (object) –

Return type

bool

__getitem__(key)

x.__getitem__(key) ⟺ x[key]

Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

__hash__ = None
__init__(*args, **kw)

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
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

classmethod __init_subclass__(**kw)

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__inverted__()

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[bidict._typing.VT, bidict._typing.KT]]

__ior__(other)

Return self|=other.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.MutableBidict[bidict._typing.KT, bidict._typing.VT]

__iter__()

Iterator over the contained keys in insertion order.

Return type

Iterator[bidict._typing.KT]

__len__()

The number of contained items.

Return type

int

__module__ = 'bidict'
__or__(other)

Return self|other.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__orig_bases__ = (bidict.OrderedBidictBase[~KT, ~VT], bidict.MutableBidict[~KT, ~VT])
__parameters__ = (~KT, ~VT)
__reduce__()

Return state information for pickling (otherwise thwarted by _invweak weakref).

__repr__()

See repr().

Return type

str

__reversed__()

Iterator over the contained keys in reverse insertion order.

Return type

Iterator[bidict._typing.KT]

__ror__(other)

Return other|self.

Parameters

other (Mapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

bidict.BidictBase[bidict._typing.KT, bidict._typing.VT]

__setitem__(key, val)

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 (bidict._typing.KT) –

  • val (bidict._typing.VT) –

Return type

None

__slots__ = ()
classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__weakref__

list of weak references to the object (if defined)

_abc_impl = <_abc._abc_data object>
static _already_have(key, val, nodeinv, nodefwd)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • nodeinv (bidict._orderedbase._Node) –

  • nodefwd (bidict._orderedbase._Node) –

Return type

bool

_dedup_item(key, val, on_dup)

Check key and val for any duplication in self.

Handle any duplication as per the passed in on_dup.

(key, val) already present is construed as a no-op, not a duplication.

If duplication is found and the corresponding OnDupAction is DROP_NEW, return None.

If duplication is found and the corresponding OnDupAction is RAISE, raise the appropriate error.

If duplication is found and the corresponding OnDupAction is DROP_OLD, or if no duplication is found, return the _DedupResult (isdupkey, isdupval, oldkey, oldval).

Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

Optional[bidict._base._DedupResult]

_fwdm_cls

alias of bidict.bidict

_init_inv()
Return type

None

_inv_cls

alias of bidict.OrderedBidict

_invm_cls

alias of bidict.bidict

_is_protocol = False
property _isinv: bool
_iter(*, reverse=False)
Parameters

reverse (bool) –

Return type

Iterator[bidict._typing.KT]

_pop(key)
Parameters

key (bidict._typing.KT) –

Return type

bidict._typing.VT

_put(key, val, on_dup)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

None

_repr_delegate

alias of list

_undo_write(dedup_result, write_result)
Parameters
  • dedup_result (bidict._base._DedupResult) –

  • write_result (bidict._base._WriteResult) –

Return type

None

_update(init, on_dup, *args, **kw)
Parameters
  • init (bool) –

  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_no_dup_check(other)
Parameters

other (bidict.BidirectionalMapping[bidict._typing.KT, bidict._typing.VT]) –

Return type

None

_update_no_rollback(on_dup, *args, **kw)
Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_update_with_rollback(on_dup, *args, **kw)

Update, rolling back on failure.

Parameters
  • on_dup (bidict.OnDup) –

  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

_write_item(key, val, dedup_result)
Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • dedup_result (bidict._base._DedupResult) –

Return type

bidict._base._WriteResult

clear()[source]

Remove all items.

Return type

None

copy()

A shallow copy of this ordered bidict.

Parameters

self (bidict._base.BT) –

Return type

bidict._base.BT

equals_order_sensitive(other)

Order-sensitive equality check.

See also __eq__() is order-insensitive

Parameters

other (object) –

Return type

bool

forceput(key, val)

Associate key with val unconditionally.

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

Parameters
  • key (bidict._typing.KT) –

  • val (bidict._typing.VT) –

Return type

None

forceupdate(*args, **kw)

Like a bulk forceput().

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
property inv: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

property inverse: bidict.BidictBase[bidict._typing.VT, bidict._typing.KT]

The inverse of this bidict.

items()

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

Return type

bidict._typing.ItemsView[bidict._typing.KT, bidict._typing.VT]

keys()

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

Return type

bidict._typing.KeysView[bidict._typing.KT]

move_to_end(key, last=True)[source]

Move an existing key to the beginning or end of this ordered bidict.

The item is moved to the end if last is True, else to the beginning.

Raises

KeyError – if the key does not exist

Parameters
  • key (bidict._typing.KT) –

  • last (bool) –

Return type

None

on_dup = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>)
pop(key, default=<_NONE>)

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 (bidict._typing.KT) –

  • default (Union[bidict._typing.VT, bidict._typing.DT]) –

Return type

Union[bidict._typing.VT, bidict._typing.DT]

popitem(last=True)[source]

x.popitem() → (k, v)

Remove and return the most recently added item as a (key, value) pair if last is True, else the least recently added item.

Raises

KeyError – if x is empty.

Parameters

last (bool) –

Return type

Tuple[bidict._typing.KT, bidict._typing.VT]

put(key, val, on_dup=OnDup(key=<RAISE>, val=<RAISE>, kv=<RAISE>))

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 (bidict._typing.KT) –

  • val (bidict._typing.VT) –

  • on_dup (bidict.OnDup) –

Return type

None

putall(items, on_dup=OnDup(key=<RAISE>, val=<RAISE>, kv=<RAISE>))

Like a bulk put().

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

Parameters
  • items (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • on_dup (bidict.OnDup) –

Return type

None

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
update(*args, **kw)

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

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

None

values()

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

Since the values of a bidict are equivalent to the keys of its inverse, this method returns a KeysView for this bidict’s inverse rather than just a ValuesView for this bidict. The KeysView offers the benefit of supporting set operations (including constant- rather than linear-time containment checks) and is just as cheap to provide as the less capable ValuesView would be.

Return type

bidict._typing.KeysView[bidict._typing.VT]

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

Bases: bidict._dup._OnDup

A 3-tuple of OnDupActions specifying how to handle the 3 kinds of duplication.

See also Values Must Be Unique

If kv is not specified, val will be used for kv.

Parameters
Return type

OnDup

__add__(value, /)

Return self+value.

__class_getitem__()

See PEP 585

__contains__(key, /)

Return key in self.

__eq__(value, /)

Return self==value.

__ge__(value, /)

Return self>=value.

__getattribute__(name, /)

Return getattr(self, name).

__getitem__(key, /)

Return self[key].

__getnewargs__()

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

__gt__(value, /)

Return self>value.

__hash__()

Return hash(self).

__iter__()

Implement iter(self).

__le__(value, /)

Return self<=value.

__len__()

Return len(self).

__lt__(value, /)

Return self<value.

__match_args__ = ('key', 'val', 'kv')
__module__ = 'bidict'
__mul__(value, /)

Return self*value.

__ne__(value, /)

Return self!=value.

static __new__(cls, key=OnDupAction.DROP_OLD, val=OnDupAction.RAISE, kv=OnDupAction.RAISE)[source]

Override to provide user-friendly default values.

Parameters
Return type

bidict.OnDup

__repr__()

Return a nicely formatted representation string

__rmul__(value, /)

Return value*self.

__slots__ = ()
_asdict()

Return a new dict which maps field names to their values.

_field_defaults = {}
_fields = ('key', 'val', 'kv')
classmethod _make(iterable)

Make a new _OnDup object from a sequence or iterable

_replace(**kwds)

Return a new _OnDup object replacing specified fields with new values

count(value, /)

Return number of occurrences of value.

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

key

Alias for field number 0

kv

Alias for field number 2

val

Alias for field number 1

class bidict.OnDupAction(value)

Bases: enum.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.

__cause__

exception cause

__context__

exception context

__delattr__(name, /)

Implement delattr(self, name).

__dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Base class for bidict exceptions.', '__weakref__': <attribute '__weakref__' of 'BidictException' objects>, '__annotations__': {}})
__getattribute__(name, /)

Return getattr(self, name).

__init__(*args, **kwargs)
__module__ = 'bidict'
__new__(**kwargs)
__reduce__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__(name, value, /)

Implement setattr(self, name, value).

__setstate__()
__str__()

Return str(self).

__suppress_context__
__traceback__
__weakref__

list of weak references to the object (if defined)

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception bidict.DuplicationError

Bases: bidict.BidictException

Base class for exceptions raised when uniqueness is violated as per the :attr:~bidict.RAISE` OnDupAction.

__annotations__ = {}
__cause__

exception cause

__context__

exception context

__delattr__(name, /)

Implement delattr(self, name).

__dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Base class for exceptions raised when uniqueness is violated\n    as per the :attr:~bidict.RAISE` :class:`~bidict.OnDupAction`.\n    ', '__annotations__': {}})
__getattribute__(name, /)

Return getattr(self, name).

__init__(*args, **kwargs)
__module__ = 'bidict'
__new__(**kwargs)
__reduce__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__(name, value, /)

Implement setattr(self, name, value).

__setstate__()
__str__()

Return str(self).

__suppress_context__
__traceback__
__weakref__

list of weak references to the object (if defined)

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception bidict.KeyDuplicationError

Bases: bidict.DuplicationError

Raised when a given key is not unique.

__annotations__ = {}
__cause__

exception cause

__context__

exception context

__delattr__(name, /)

Implement delattr(self, name).

__dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Raised when a given key is not unique.', '__annotations__': {}})
__getattribute__(name, /)

Return getattr(self, name).

__init__(*args, **kwargs)
__module__ = 'bidict'
__new__(**kwargs)
__reduce__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__(name, value, /)

Implement setattr(self, name, value).

__setstate__()
__str__()

Return str(self).

__suppress_context__
__traceback__
__weakref__

list of weak references to the object (if defined)

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception bidict.ValueDuplicationError

Bases: bidict.DuplicationError

Raised when a given value is not unique.

__annotations__ = {}
__cause__

exception cause

__context__

exception context

__delattr__(name, /)

Implement delattr(self, name).

__dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Raised when a given value is not unique.', '__annotations__': {}})
__getattribute__(name, /)

Return getattr(self, name).

__init__(*args, **kwargs)
__module__ = 'bidict'
__new__(**kwargs)
__reduce__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__(name, value, /)

Implement setattr(self, name, value).

__setstate__()
__str__()

Return str(self).

__suppress_context__
__traceback__
__weakref__

list of weak references to the object (if defined)

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception bidict.KeyAndValueDuplicationError

Bases: bidict.KeyDuplicationError, bidict.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__ = {}
__cause__

exception cause

__context__

exception context

__delattr__(name, /)

Implement delattr(self, name).

__dict__ = mappingproxy({'__module__': 'bidict', '__doc__': "Raised when a given item's key and value are not unique.\n\n    That is, its key duplicates that of another item,\n    and its value duplicates that of a different other item.\n    ", '__annotations__': {}})
__getattribute__(name, /)

Return getattr(self, name).

__init__(*args, **kwargs)
__module__ = 'bidict'
__new__(**kwargs)
__reduce__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__(name, value, /)

Implement setattr(self, name, value).

__setstate__()
__str__()

Return str(self).

__suppress_context__
__traceback__
__weakref__

list of weak references to the object (if defined)

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

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 (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

Return type

Iterable[Tuple[bidict._typing.VT, bidict._typing.KT]]

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 = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>)

A 3-tuple of OnDupActions specifying how to handle the 3 kinds of duplication.

See also Values Must Be Unique

If kv is not specified, val will be used for kv.

bidict.ON_DUP_RAISE = OnDup(key=<RAISE>, val=<RAISE>, kv=<RAISE>)

A 3-tuple of OnDupActions specifying how to handle the 3 kinds of duplication.

See also Values Must Be Unique

If kv is not specified, val will be used for kv.

bidict.ON_DUP_DROP_OLD = OnDup(key=<DROP_OLD>, val=<DROP_OLD>, kv=<DROP_OLD>)

A 3-tuple of OnDupActions specifying how to handle the 3 kinds of duplication.

See also Values Must Be Unique

If kv is not specified, val will be used for kv.

bidict._iter._iteritems_mapping_or_iterable(arg)[source]

Yield the items in arg.

If arg is a Mapping, return an iterator over its items. Otherwise return an iterator over arg itself.

Parameters

arg (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

Return type

Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]

bidict._iter._iteritems_args_kw(*args, **kw)[source]

Yield the items from the positional argument (if given) and then any from kw.

Raises

TypeError – if more than one positional argument is given.

Parameters
  • args (Union[Mapping[bidict._typing.KT, bidict._typing.VT], Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]]) –

  • kw (bidict._typing.VT) –

Return type

Iterable[Tuple[bidict._typing.KT, bidict._typing.VT]]

bidict.__version__

The version of bidict represented as a string.