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.BidictBase(*args, **kw)

Bases: bidict.BidirectionalMapping

Base class implementing BidirectionalMapping.

__abstractmethods__ = frozenset()
__class__

alias of abc.ABCMeta

classmethod __class_getitem__(params)
__contains__(key)
__copy__() → BT

A shallow copy.

__delattr__

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__(other: object) → bool[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()

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__getitem__(key: KT) → VT[source]

x.__getitem__(key) ⟺ x[key]

__getstate__() → dict[source]

Needed to enable pickling due to use of __slots__ and weakrefs.

See also object.__getstate__()

__gt__

Return self>value.

__hash__ = None
__init__(*args, **kw) → None[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.

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__() → Iterator[Tuple[VT, KT]]

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()

__iter__() → Iterator[KT][source]

Iterator over the contained keys.

__le__

Return self<=value.

__len__() → int[source]

The number of contained items.

__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

static __new__(cls, *args, **kwds)

Create and return a new object. See help(type) for accurate signature.

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

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__() → str[source]

See repr().

__reversed__() → Iterator[KT][source]

Iterator over the contained keys in reverse order.

__setattr__

Implement setattr(self, name, value).

__setstate__(state: dict) → None[source]

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__slots__ = ['_fwdm', '_invm', '_inv', '_invweak']
__str__

Return str(self).

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_data object>
static _already_have(key: KT, val: VT, oldkey: Union[KT, bidict._typing._NONE], oldval: Union[VT, bidict._typing._NONE]) → bool[source]
_dedup_item(key: KT, val: VT, on_dup: bidict.OnDup) → Optional[bidict._base._DedupResult][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).

_fwdm
_fwdm_cls

alias of builtins.dict

_init_inv() → None[source]
_inv
_invm
_invm_cls

alias of builtins.dict

_invweak
_is_protocol = False
_isinv
_pop(key: KT) → VT[source]
_put(key: KT, val: VT, on_dup: bidict.OnDup) → None[source]
_repr_delegate

alias of builtins.dict

_undo_write(dedup_result: bidict._base._DedupResult, write_result: bidict._base._WriteResult) → None[source]
_update(init: bool, on_dup: bidict.OnDup, *args, **kw) → None[source]
_update_no_dup_check(other: bidict.BidirectionalMapping[~KT, ~VT][KT, VT]) → None[source]
_update_no_rollback(on_dup: bidict.OnDup, *args, **kw) → None[source]
_update_with_rollback(on_dup: bidict.OnDup, *args, **kw) → None[source]

Update, rolling back on failure.

_write_item(key: KT, val: VT, dedup_result: bidict._base._DedupResult) → bidict._base._WriteResult[source]
copy() → BT[source]

A shallow copy.

equals_order_sensitive(other: object) → bool[source]

Order-sensitive equality check.

See also __eq__() is order-insensitive

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
inv

The inverse of this bidict.

inverse

The inverse of this bidict.

items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
on_dup = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>)
values() → AbstractSet[VT]

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

Override the implementation inherited from Mapping. Because the values of a BidirectionalMapping are the keys of its inverse, this returns a KeysView rather than a ValuesView, which has the advantages of constant-time containment checks and supporting set operations.

exception bidict.BidictException

Bases: Exception

Base class for bidict exceptions.

__cause__

exception cause

__class__

alias of builtins.type

__context__

exception context

__delattr__

Implement delattr(self, name).

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

Default dir() implementation.

__eq__

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__hash__

Return hash(self).

__init__

Initialize self. See help(type(self)) for accurate signature.

__init_subclass__()

This method is called when a class is subclassed.

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

__le__

Return self<=value.

__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__

Return repr(self).

__setattr__

Implement setattr(self, name, value).

__setstate__()
__sizeof__()

Size of object in memory, in bytes.

__str__

Return str(self).

__subclasshook__()

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).

__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.

class bidict.BidirectionalMapping

Bases: collections.abc.Mapping, typing.Generic

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({'inverse', '__iter__', '__len__', '__getitem__'})
__class__

alias of abc.ABCMeta

classmethod __class_getitem__(params)
__contains__(key)
__delattr__

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__(other)

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__getitem__(key)
__gt__

Return self>value.

__hash__ = None
__init__

Initialize self. See help(type(self)) for accurate signature.

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__() → Iterator[Tuple[VT, KT]][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()

__iter__()
__le__

Return self<=value.

__len__()
__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

static __new__(cls, *args, **kwds)

Create and return a new object. See help(type) for accurate signature.

__orig_bases__ = (typing.Mapping[~KT, ~VT],)
__parameters__ = (~KT, ~VT)
__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__

Return repr(self).

__reversed__ = None
__setattr__

Implement setattr(self, name, value).

__sizeof__()

Size of object in memory, in bytes.

__slots__ = ()
__str__

Return str(self).

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_data object>
_is_protocol = False
get(k[, d]) → D[k] if k in D, else d. d defaults to None.
inverse

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() → AbstractSet[VT][source]

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

Override the implementation inherited from Mapping. Because the values of a BidirectionalMapping are the keys of its inverse, this returns a KeysView rather than a ValuesView, which has the advantages of constant-time containment checks and supporting set operations.

exception bidict.DuplicationError

Bases: bidict.BidictException

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

__cause__

exception cause

__class__

alias of builtins.type

__context__

exception context

__delattr__

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 '})
__dir__()

Default dir() implementation.

__eq__

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__hash__

Return hash(self).

__init__

Initialize self. See help(type(self)) for accurate signature.

__init_subclass__()

This method is called when a class is subclassed.

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

__le__

Return self<=value.

__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__

Return repr(self).

__setattr__

Implement setattr(self, name, value).

__setstate__()
__sizeof__()

Size of object in memory, in bytes.

__str__

Return str(self).

__subclasshook__()

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).

__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.

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

Bases: bidict.OrderedBidictBase

Hashable, immutable, ordered bidict type.

__abstractmethods__ = frozenset()
__annotations__ = {}
__class__

alias of abc.ABCMeta

classmethod __class_getitem__(params)
__contains__(key)
__copy__() → BT

A shallow copy of this ordered bidict.

__delattr__

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__(other: object) → bool

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()

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__getitem__(key: KT) → VT

x.__getitem__(key) ⟺ x[key]

__getstate__() → dict

Needed to enable pickling due to use of __slots__ and weakrefs.

See also object.__getstate__()

__gt__

Return self>value.

__hash__() → int

The hash of this bidict as determined by its items.

__init__(*args, **kw) → None

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.

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__() → Iterator[Tuple[VT, KT]]

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()

__iter__() → Iterator[KT][source]

Iterator over the contained keys in insertion order.

__le__

Return self<=value.

__len__() → int

The number of contained items.

__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

static __new__(cls, *args, **kwds)

Create and return a new object. See help(type) for accurate signature.

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

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__() → str

See repr().

__reversed__() → Iterator[KT]

Iterator over the contained keys in reverse insertion order.

__setattr__

Implement setattr(self, name, value).

__setstate__(state: dict) → None

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__slots__ = ('_hash',)
__str__

Return str(self).

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_data object>
static _already_have(key: KT, val: VT, nodeinv: bidict._orderedbase._Node, nodefwd: bidict._orderedbase._Node) → bool
_dedup_item(key: KT, val: VT, on_dup: bidict.OnDup) → Optional[bidict._base._DedupResult]

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).

_fwdm
_fwdm_cls

alias of bidict

_hash
_init_inv() → None
_inv
_inv_cls

alias of FrozenOrderedBidict

_invm
_invm_cls

alias of bidict

_invweak
_is_protocol = False
_isinv
_iter(*, reverse: bool = False) → Iterator[KT][source]
_pop(key: KT) → VT
_put(key: KT, val: VT, on_dup: bidict.OnDup) → None
_repr_delegate

alias of builtins.list

_sntl
_undo_write(dedup_result: bidict._base._DedupResult, write_result: bidict._base._WriteResult) → None
_update(init: bool, on_dup: bidict.OnDup, *args, **kw) → None
_update_no_dup_check(other: bidict.BidirectionalMapping[~KT, ~VT][KT, VT]) → None
_update_no_rollback(on_dup: bidict.OnDup, *args, **kw) → None
_update_with_rollback(on_dup: bidict.OnDup, *args, **kw) → None

Update, rolling back on failure.

_write_item(key: KT, val: VT, dedup_result: bidict._base._DedupResult) → bidict._base._WriteResult
copy() → BT

A shallow copy of this ordered bidict.

equals_order_sensitive(other: object) → bool

Order-sensitive equality check.

See also __eq__() is order-insensitive

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
inv

The inverse of this bidict.

inverse

The inverse of this bidict.

items() → a set-like object providing a view on D's items
keys() → KeysView[KT][source]

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

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

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

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.

__cause__

exception cause

__class__

alias of builtins.type

__context__

exception context

__delattr__

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 "})
__dir__()

Default dir() implementation.

__eq__

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__hash__

Return hash(self).

__init__

Initialize self. See help(type(self)) for accurate signature.

__init_subclass__()

This method is called when a class is subclassed.

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

__le__

Return self<=value.

__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__

Return repr(self).

__setattr__

Implement setattr(self, name, value).

__setstate__()
__sizeof__()

Size of object in memory, in bytes.

__str__

Return str(self).

__subclasshook__()

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).

__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.

__cause__

exception cause

__class__

alias of builtins.type

__context__

exception context

__delattr__

Implement delattr(self, name).

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

Default dir() implementation.

__eq__

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__hash__

Return hash(self).

__init__

Initialize self. See help(type(self)) for accurate signature.

__init_subclass__()

This method is called when a class is subclassed.

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

__le__

Return self<=value.

__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__

Return repr(self).

__setattr__

Implement setattr(self, name, value).

__setstate__()
__sizeof__()

Size of object in memory, in bytes.

__str__

Return str(self).

__subclasshook__()

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).

__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.

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

Bases: bidict.BidictBase, bidict.MutableBidirectionalMapping

Base class for mutable bidirectional mappings.

_MutableMapping__marker = <object object>
__abstractmethods__ = frozenset()
__class__

alias of abc.ABCMeta

classmethod __class_getitem__(params)
__contains__(key)
__copy__() → BT

A shallow copy.

__delattr__

Implement delattr(self, name).

__delitem__(key: KT) → None[source]

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

__dir__()

Default dir() implementation.

__eq__(other: object) → bool

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()

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__getitem__(key: KT) → VT

x.__getitem__(key) ⟺ x[key]

__getstate__() → dict

Needed to enable pickling due to use of __slots__ and weakrefs.

See also object.__getstate__()

__gt__

Return self>value.

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

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.

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__() → Iterator[Tuple[VT, KT]]

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()

__iter__() → Iterator[KT]

Iterator over the contained keys.

__le__

Return self<=value.

__len__() → int

The number of contained items.

__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

static __new__(cls, *args, **kwds)

Create and return a new object. See help(type) for accurate signature.

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

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__() → str

See repr().

__reversed__() → Iterator[KT]

Iterator over the contained keys in reverse order.

__setattr__

Implement setattr(self, name, value).

__setitem__(key: KT, val: VT) → None[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:
__setstate__(state: dict) → None

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__slots__ = ()
__str__

Return str(self).

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_data object>
static _already_have(key: KT, val: VT, oldkey: Union[KT, bidict._typing._NONE], oldval: Union[VT, bidict._typing._NONE]) → bool
_dedup_item(key: KT, val: VT, on_dup: bidict.OnDup) → Optional[bidict._base._DedupResult]

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).

_fwdm
_fwdm_cls

alias of builtins.dict

_init_inv() → None
_inv
_inv_cls

alias of MutableBidict

_invm
_invm_cls

alias of builtins.dict

_invweak
_is_protocol = False
_isinv
_pop(key: KT) → VT
_put(key: KT, val: VT, on_dup: bidict.OnDup) → None
_repr_delegate

alias of builtins.dict

_undo_write(dedup_result: bidict._base._DedupResult, write_result: bidict._base._WriteResult) → None
_update(init: bool, on_dup: bidict.OnDup, *args, **kw) → None
_update_no_dup_check(other: bidict.BidirectionalMapping[~KT, ~VT][KT, VT]) → None
_update_no_rollback(on_dup: bidict.OnDup, *args, **kw) → None
_update_with_rollback(on_dup: bidict.OnDup, *args, **kw) → None

Update, rolling back on failure.

_write_item(key: KT, val: VT, dedup_result: bidict._base._DedupResult) → bidict._base._WriteResult
clear() → None[source]

Remove all items.

copy() → BT

A shallow copy.

equals_order_sensitive(other: object) → bool

Order-sensitive equality check.

See also __eq__() is order-insensitive

forceput(key: KT, val: VT) → None[source]

Associate key with val unconditionally.

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

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

Like a bulk forceput().

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
inv

The inverse of this bidict.

inverse

The inverse of this bidict.

items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
on_dup = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>)
pop(key: KT, default: Union[VT, DT] = <_NONE>) → Union[VT, DT][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.
popitem() → Tuple[KT, VT][source]

x.popitem() → (k, v)

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

Raises:KeyError – if x is empty.
put(key: KT, val: VT, on_dup: bidict.OnDup = OnDup(key=<RAISE>, val=<RAISE>, kv=<RAISE>)) → None[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:
putall(items: Union[Mapping[KT, VT], Iterable[Tuple[KT, VT]]], on_dup: bidict.OnDup = OnDup(key=<RAISE>, val=<RAISE>, kv=<RAISE>)) → None[source]

Like a bulk put().

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

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

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

values() → AbstractSet[VT]

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

Override the implementation inherited from Mapping. Because the values of a BidirectionalMapping are the keys of its inverse, this returns a KeysView rather than a ValuesView, which has the advantages of constant-time containment checks and supporting set operations.

class bidict.MutableBidirectionalMapping

Bases: bidict.BidirectionalMapping, collections.abc.MutableMapping, typing.Generic

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

_MutableMapping__marker = <object object>
__abstractmethods__ = frozenset({'inverse', '__getitem__', '__len__', '__iter__', '__setitem__', '__delitem__'})
__class__

alias of abc.ABCMeta

classmethod __class_getitem__(params)
__contains__(key)
__delattr__

Implement delattr(self, name).

__delitem__(key)
__dir__()

Default dir() implementation.

__eq__(other)

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__getitem__(key)
__gt__

Return self>value.

__hash__ = None
__init__

Initialize self. See help(type(self)) for accurate signature.

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__() → Iterator[Tuple[VT, KT]]

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()

__iter__()
__le__

Return self<=value.

__len__()
__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

static __new__(cls, *args, **kwds)

Create and return a new object. See help(type) for accurate signature.

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

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__

Return repr(self).

__reversed__ = None
__setattr__

Implement setattr(self, name, value).

__setitem__(key, value)
__sizeof__()

Size of object in memory, in bytes.

__slots__ = ()
__str__

Return str(self).

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_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.
inverse

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() → AbstractSet[VT]

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

Override the implementation inherited from Mapping. Because the values of a BidirectionalMapping are the keys of its inverse, this returns a KeysView rather than a ValuesView, which has the advantages of constant-time containment checks and supporting set operations.

class bidict.OnDup

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.

__add__

Return self+value.

__class__

alias of builtins.type

__contains__

Return key in self.

__delattr__

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__getitem__

Return self[key].

__getnewargs__()

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

__gt__

Return self>value.

__hash__

Return hash(self).

__init__

Initialize self. See help(type(self)) for accurate signature.

__init_subclass__()

This method is called when a class is subclassed.

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

__iter__

Implement iter(self).

__le__

Return self<=value.

__len__

Return len(self).

__lt__

Return self<value.

__module__ = 'bidict'
__mul__

Return self*value.

__ne__

Return self!=value.

static __new__(cls, key: bidict.OnDupAction = <DROP_OLD>, val: bidict.OnDupAction = <RAISE>, kv: bidict.OnDupAction = <RAISE>) → bidict.OnDup[source]

Override to provide user-friendly default values.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return a nicely formatted representation string

__rmul__

Return value*self.

__setattr__

Implement setattr(self, name, value).

__sizeof__()

Size of object in memory, in bytes.

__slots__ = ()
__str__

Return str(self).

__subclasshook__()

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).

_asdict()

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

_field_defaults = {}
_fields = ('key', 'val', 'kv')
_fields_defaults = {}
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()

Return number of occurrences of value.

index()

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

Bases: enum.Enum

An action to take to prevent duplication from occurring.

DROP_NEW = 'DROP_NEW'
DROP_OLD = 'DROP_OLD'
RAISE = 'RAISE'
__class__

alias of enum.EnumMeta

__members__ = mappingproxy({'RAISE': <RAISE>, 'DROP_OLD': <DROP_OLD>, 'DROP_NEW': <DROP_NEW>})
__module__ = 'bidict'
class bidict.OrderedBidict(*args, **kw)

Bases: bidict.OrderedBidictBase, bidict.MutableBidict

Mutable bidict type that maintains items in insertion order.

_MutableMapping__marker = <object object>
__abstractmethods__ = frozenset()
__annotations__ = {}
__class__

alias of abc.ABCMeta

classmethod __class_getitem__(params)
__contains__(key)
__copy__() → BT

A shallow copy of this ordered bidict.

__delattr__

Implement delattr(self, name).

__delitem__(key: KT) → None

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

__dir__()

Default dir() implementation.

__eq__(other: object) → bool

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()

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__getitem__(key: KT) → VT

x.__getitem__(key) ⟺ x[key]

__getstate__() → dict

Needed to enable pickling due to use of __slots__ and weakrefs.

See also object.__getstate__()

__gt__

Return self>value.

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

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.

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__() → Iterator[Tuple[VT, KT]]

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()

__iter__() → Iterator[KT]

Iterator over the contained keys in insertion order.

__le__

Return self<=value.

__len__() → int

The number of contained items.

__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

static __new__(cls, *args, **kwds)

Create and return a new object. See help(type) for accurate signature.

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

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__() → str

See repr().

__reversed__() → Iterator[KT]

Iterator over the contained keys in reverse insertion order.

__setattr__

Implement setattr(self, name, value).

__setitem__(key: KT, val: VT) → None

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:
__setstate__(state: dict) → None

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__slots__ = ()
__str__

Return str(self).

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_data object>
static _already_have(key: KT, val: VT, nodeinv: bidict._orderedbase._Node, nodefwd: bidict._orderedbase._Node) → bool
_dedup_item(key: KT, val: VT, on_dup: bidict.OnDup) → Optional[bidict._base._DedupResult]

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).

_fwdm
_fwdm_cls

alias of bidict

_init_inv() → None
_inv
_inv_cls

alias of OrderedBidict

_invm
_invm_cls

alias of bidict

_invweak
_is_protocol = False
_isinv
_iter(*, reverse: bool = False) → Iterator[KT]
_pop(key: KT) → VT
_put(key: KT, val: VT, on_dup: bidict.OnDup) → None
_repr_delegate

alias of builtins.list

_sntl
_undo_write(dedup_result: bidict._base._DedupResult, write_result: bidict._base._WriteResult) → None
_update(init: bool, on_dup: bidict.OnDup, *args, **kw) → None
_update_no_dup_check(other: bidict.BidirectionalMapping[~KT, ~VT][KT, VT]) → None
_update_no_rollback(on_dup: bidict.OnDup, *args, **kw) → None
_update_with_rollback(on_dup: bidict.OnDup, *args, **kw) → None

Update, rolling back on failure.

_write_item(key: KT, val: VT, dedup_result: bidict._base._DedupResult) → bidict._base._WriteResult
clear() → None[source]

Remove all items.

copy() → BT

A shallow copy of this ordered bidict.

equals_order_sensitive(other: object) → bool

Order-sensitive equality check.

See also __eq__() is order-insensitive

forceput(key: KT, val: VT) → None

Associate key with val unconditionally.

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

forceupdate(*args, **kw) → None

Like a bulk forceput().

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
inv

The inverse of this bidict.

inverse

The inverse of this bidict.

items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
move_to_end(key: KT, last: bool = True) → None[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
on_dup = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>)
pop(key: KT, default: Union[VT, DT] = <_NONE>) → Union[VT, DT]

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.
popitem(last: bool = True) → Tuple[KT, VT][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.
put(key: KT, val: VT, on_dup: bidict.OnDup = OnDup(key=<RAISE>, val=<RAISE>, kv=<RAISE>)) → None

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

Like a bulk put().

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

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

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

values() → AbstractSet[VT]

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

Override the implementation inherited from Mapping. Because the values of a BidirectionalMapping are the keys of its inverse, this returns a KeysView rather than a ValuesView, which has the advantages of constant-time containment checks and supporting set operations.

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

Bases: bidict.BidictBase

Base class implementing an ordered BidirectionalMapping.

__abstractmethods__ = frozenset()
__annotations__ = {}
__class__

alias of abc.ABCMeta

classmethod __class_getitem__(params)
__contains__(key)
__copy__() → BT

A shallow copy of this ordered bidict.

__delattr__

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__(other: object) → bool

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()

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__getitem__(key: KT) → VT[source]

x.__getitem__(key) ⟺ x[key]

__getstate__() → dict

Needed to enable pickling due to use of __slots__ and weakrefs.

See also object.__getstate__()

__gt__

Return self>value.

__hash__ = None
__init__(*args, **kw) → None[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.

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__() → Iterator[Tuple[VT, KT]]

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()

__iter__() → Iterator[KT][source]

Iterator over the contained keys in insertion order.

__le__

Return self<=value.

__len__() → int

The number of contained items.

__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

static __new__(cls, *args, **kwds)

Create and return a new object. See help(type) for accurate signature.

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

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__() → str

See repr().

__reversed__() → Iterator[KT][source]

Iterator over the contained keys in reverse insertion order.

__setattr__

Implement setattr(self, name, value).

__setstate__(state: dict) → None

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__slots__ = ('_sntl',)
__str__

Return str(self).

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_data object>
static _already_have(key: KT, val: VT, nodeinv: bidict._orderedbase._Node, nodefwd: bidict._orderedbase._Node) → bool[source]
_dedup_item(key: KT, val: VT, on_dup: bidict.OnDup) → Optional[bidict._base._DedupResult]

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).

_fwdm
_fwdm_cls

alias of bidict

_init_inv() → None[source]
_inv
_inv_cls

alias of OrderedBidictBase

_invm
_invm_cls

alias of bidict

_invweak
_is_protocol = False
_isinv
_iter(*, reverse: bool = False) → Iterator[KT][source]
_pop(key: KT) → VT[source]
_put(key: KT, val: VT, on_dup: bidict.OnDup) → None
_repr_delegate

alias of builtins.list

_sntl
_undo_write(dedup_result: bidict._base._DedupResult, write_result: bidict._base._WriteResult) → None[source]
_update(init: bool, on_dup: bidict.OnDup, *args, **kw) → None
_update_no_dup_check(other: bidict.BidirectionalMapping[~KT, ~VT][KT, VT]) → None
_update_no_rollback(on_dup: bidict.OnDup, *args, **kw) → None
_update_with_rollback(on_dup: bidict.OnDup, *args, **kw) → None

Update, rolling back on failure.

_write_item(key: KT, val: VT, dedup_result: bidict._base._DedupResult) → bidict._base._WriteResult[source]
copy() → BT[source]

A shallow copy of this ordered bidict.

equals_order_sensitive(other: object) → bool

Order-sensitive equality check.

See also __eq__() is order-insensitive

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
inv

The inverse of this bidict.

inverse

The inverse of this bidict.

items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
on_dup = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>)
values() → AbstractSet[VT]

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

Override the implementation inherited from Mapping. Because the values of a BidirectionalMapping are the keys of its inverse, this returns a KeysView rather than a ValuesView, which has the advantages of constant-time containment checks and supporting set operations.

exception bidict.ValueDuplicationError

Bases: bidict.DuplicationError

Raised when a given value is not unique.

__cause__

exception cause

__class__

alias of builtins.type

__context__

exception context

__delattr__

Implement delattr(self, name).

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

Default dir() implementation.

__eq__

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__hash__

Return hash(self).

__init__

Initialize self. See help(type(self)) for accurate signature.

__init_subclass__()

This method is called when a class is subclassed.

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

__le__

Return self<=value.

__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__

Return repr(self).

__setattr__

Implement setattr(self, name, value).

__setstate__()
__sizeof__()

Size of object in memory, in bytes.

__str__

Return str(self).

__subclasshook__()

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).

__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.

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

Bases: bidict._delegating._DelegatingBidict, bidict.MutableBidict

Base class for mutable bidirectional mappings.

_MutableMapping__marker = <object object>
__abstractmethods__ = frozenset()
__class__

alias of abc.ABCMeta

classmethod __class_getitem__(params)
__contains__(key)
__copy__() → BT

A shallow copy.

__delattr__

Implement delattr(self, name).

__delitem__(key: KT) → None

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

__dir__()

Default dir() implementation.

__eq__(other: object) → bool

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()

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__getitem__(key: KT) → VT

x.__getitem__(key) ⟺ x[key]

__getstate__() → dict

Needed to enable pickling due to use of __slots__ and weakrefs.

See also object.__getstate__()

__gt__

Return self>value.

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

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.

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__() → Iterator[Tuple[VT, KT]]

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()

__iter__() → Iterator[KT]

Iterator over the contained keys.

__le__

Return self<=value.

__len__() → int

The number of contained items.

__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

static __new__(cls, *args, **kwds)

Create and return a new object. See help(type) for accurate signature.

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

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__() → str

See repr().

__reversed__() → Iterator[KT]

Iterator over the contained keys in reverse order.

__setattr__

Implement setattr(self, name, value).

__setitem__(key: KT, val: VT) → None

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:
__setstate__(state: dict) → None

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__slots__ = ()
__str__

Return str(self).

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_data object>
static _already_have(key: KT, val: VT, oldkey: Union[KT, bidict._typing._NONE], oldval: Union[VT, bidict._typing._NONE]) → bool
_dedup_item(key: KT, val: VT, on_dup: bidict.OnDup) → Optional[bidict._base._DedupResult]

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).

_fwdm
_fwdm_cls

alias of builtins.dict

_init_inv() → None
_inv
_inv_cls

alias of bidict

_invm
_invm_cls

alias of builtins.dict

_invweak
_is_protocol = False
_isinv
_pop(key: KT) → VT
_put(key: KT, val: VT, on_dup: bidict.OnDup) → None
_repr_delegate

alias of builtins.dict

_undo_write(dedup_result: bidict._base._DedupResult, write_result: bidict._base._WriteResult) → None
_update(init: bool, on_dup: bidict.OnDup, *args, **kw) → None
_update_no_dup_check(other: bidict.BidirectionalMapping[~KT, ~VT][KT, VT]) → None
_update_no_rollback(on_dup: bidict.OnDup, *args, **kw) → None
_update_with_rollback(on_dup: bidict.OnDup, *args, **kw) → None

Update, rolling back on failure.

_write_item(key: KT, val: VT, dedup_result: bidict._base._DedupResult) → bidict._base._WriteResult
clear() → None

Remove all items.

copy() → BT

A shallow copy.

equals_order_sensitive(other: object) → bool

Order-sensitive equality check.

See also __eq__() is order-insensitive

forceput(key: KT, val: VT) → None

Associate key with val unconditionally.

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

forceupdate(*args, **kw) → None

Like a bulk forceput().

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
inv

The inverse of this bidict.

inverse

The inverse of this bidict.

items() → ItemsView[KT, VT]

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

keys() → KeysView[KT]

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

on_dup = OnDup(key=<DROP_OLD>, val=<RAISE>, kv=<RAISE>)
pop(key: KT, default: Union[VT, DT] = <_NONE>) → Union[VT, DT]

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.
popitem() → Tuple[KT, VT]

x.popitem() → (k, v)

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

Raises:KeyError – if x is empty.
put(key: KT, val: VT, on_dup: bidict.OnDup = OnDup(key=<RAISE>, val=<RAISE>, kv=<RAISE>)) → None

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

Like a bulk put().

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

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

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

values() → KeysView[VT]

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

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

Bases: bidict._delegating._DelegatingBidict

Immutable, hashable bidict type.

__abstractmethods__ = frozenset()
__class__

alias of abc.ABCMeta

classmethod __class_getitem__(params)
__contains__(key)
__copy__() → BT

A shallow copy.

__delattr__

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__(other: object) → bool

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()

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__getitem__(key: KT) → VT

x.__getitem__(key) ⟺ x[key]

__getstate__() → dict

Needed to enable pickling due to use of __slots__ and weakrefs.

See also object.__getstate__()

__gt__

Return self>value.

__hash__() → int[source]

The hash of this bidict as determined by its items.

__init__(*args, **kw) → None

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.

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__() → Iterator[Tuple[VT, KT]]

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()

__iter__() → Iterator[KT]

Iterator over the contained keys.

__le__

Return self<=value.

__len__() → int

The number of contained items.

__lt__

Return self<value.

__module__ = 'bidict'
__ne__

Return self!=value.

static __new__(cls, *args, **kwds)

Create and return a new object. See help(type) for accurate signature.

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

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__() → str

See repr().

__reversed__() → Iterator[KT]

Iterator over the contained keys in reverse order.

__setattr__

Implement setattr(self, name, value).

__setstate__(state: dict) → None

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__slots__ = ('_hash',)
__str__

Return str(self).

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_data object>
static _already_have(key: KT, val: VT, oldkey: Union[KT, bidict._typing._NONE], oldval: Union[VT, bidict._typing._NONE]) → bool
_dedup_item(key: KT, val: VT, on_dup: bidict.OnDup) → Optional[bidict._base._DedupResult]

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).

_fwdm
_fwdm_cls

alias of builtins.dict

_hash
_init_inv() → None
_inv
_inv_cls

alias of frozenbidict

_invm
_invm_cls

alias of builtins.dict

_invweak
_is_protocol = False
_isinv
_pop(key: KT) → VT
_put(key: KT, val: VT, on_dup: bidict.OnDup) → None
_repr_delegate

alias of builtins.dict

_undo_write(dedup_result: bidict._base._DedupResult, write_result: bidict._base._WriteResult) → None
_update(init: bool, on_dup: bidict.OnDup, *args, **kw) → None
_update_no_dup_check(other: bidict.BidirectionalMapping[~KT, ~VT][KT, VT]) → None
_update_no_rollback(on_dup: bidict.OnDup, *args, **kw) → None
_update_with_rollback(on_dup: bidict.OnDup, *args, **kw) → None

Update, rolling back on failure.

_write_item(key: KT, val: VT, dedup_result: bidict._base._DedupResult) → bidict._base._WriteResult
copy() → BT

A shallow copy.

equals_order_sensitive(other: object) → bool

Order-sensitive equality check.

See also __eq__() is order-insensitive

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
inv

The inverse of this bidict.

inverse

The inverse of this bidict.

items() → ItemsView[KT, VT]

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

keys() → KeysView[KT]

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

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

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

bidict.inverted(arg: Union[Mapping[KT, VT], Iterable[Tuple[KT, VT]]]) → Iterable[Tuple[VT, KT]]

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__

bidict.namedbidict(typename: str, keyname: str, valname: str, *, base_type: Type[bidict.BidirectionalMapping[~KT, ~VT][KT, VT]] = <class 'bidict.bidict'>) → Type[bidict.BidirectionalMapping[~KT, ~VT][KT, VT]]

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:
bidict.RAISE = <RAISE>

An action to take to prevent duplication from occurring.

bidict.DROP_OLD = <DROP_OLD>

An action to take to prevent duplication from occurring.

bidict.DROP_NEW = <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: Union[Mapping[KT, VT], Iterable[Tuple[KT, VT]]]) → Iterable[Tuple[KT, VT]][source]

Yield the items in arg.

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

bidict._iter._iteritems_args_kw(*args, **kw) → Iterable[Tuple[KT, VT]][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.
bidict.__version__

The version of bidict represented as a string.