API#
This page contains auto-generated documentation from the bidict source code.
bidict#
The bidirectional mapping library for Python.
bidict by example:
>>> from bidict import bidict
>>> element_by_symbol = bidict({'H': 'hydrogen'})
>>> element_by_symbol['H']
'hydrogen'
>>> element_by_symbol.inverse['hydrogen']
'H'
Please see https://github.com/jab/bidict for the most up-to-date code and https://bidict.readthedocs.io for the most up-to-date documentation if you are reading this elsewhere.
- class bidict.BidirectionalMapping#
Bases:
Mapping
[KT
,VT
]Abstract base class for bidirectional mapping types.
Extends
collections.abc.Mapping
primarily by adding the (abstract)inverse
property, which implementers ofBidirectionalMapping
should override to return a reference to the inverseBidirectionalMapping
instance.- __abstractmethods__ = frozenset({'__getitem__', '__iter__', '__len__', 'inverse'})#
- classmethod __class_getitem__()#
Represent a PEP 585 generic type
E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
- __contains__(key)#
- __eq__(other)#
Return self==value.
- abstract __getitem__(key)#
- __hash__ = None#
- __init_subclass__()#
Function to initialize 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()
- 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).
- get(k[, d]) D[k] if k in D, else d. d defaults to None. #
- abstract property inverse: BidirectionalMapping[VT, KT]#
The inverse of this bidirectional mapping instance.
See also
bidict.BidictBase.inverse
,bidict.BidictBase.inv
- Raises:
NotImplementedError – Meant to be overridden in subclasses.
- 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:
BidirectionalMapping
[KT
,VT
],MutableMapping
[KT
,VT
]Abstract base class for mutable bidirectional mapping types.
- __abstractmethods__ = frozenset({'__delitem__', '__getitem__', '__iter__', '__len__', '__setitem__', 'inverse'})#
- __annotations__ = {}#
- classmethod __class_getitem__()#
Represent a PEP 585 generic type
E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
- __contains__(key)#
- abstract __delitem__(key)#
- __eq__(other)#
Return self==value.
- abstract __getitem__(key)#
- __hash__ = None#
- __init_subclass__()#
Function to initialize 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()
- 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).
- 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: BidirectionalMapping[VT, KT]#
The inverse of this bidirectional mapping instance.
See also
bidict.BidictBase.inverse
,bidict.BidictBase.inv
- Raises:
NotImplementedError – Meant to be overridden in subclasses.
- 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(arg=(), /, **kw)#
Bases:
BidirectionalMapping
[KT
,VT
]Base class implementing
BidirectionalMapping
.- Parameters:
arg (MapOrItems[KT, VT]) –
kw (VT) –
- __abstractmethods__ = frozenset({})#
- __annotations__ = {'__reversed__': 't.ClassVar[t.Any]', '_fwdm': 't.MutableMapping[KT, VT]', '_fwdm_cls': 't.ClassVar[type[t.MutableMapping[t.Any, t.Any]]]', '_inv_cls': 't.ClassVar[type[BidictBase[t.Any, t.Any]]]', '_invm': 't.MutableMapping[VT, KT]', '_invm_cls': 't.ClassVar[type[t.MutableMapping[t.Any, t.Any]]]'}#
- classmethod __class_getitem__()#
Represent a PEP 585 generic type
E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
- __copy__()[source]#
Used for the copy protocol. See the
copy
module.- Parameters:
self (BT) –
- Return type:
BT
- __dict__ = mappingproxy({'__module__': 'bidict', '__annotations__': {'_fwdm': 't.MutableMapping[KT, VT]', '_invm': 't.MutableMapping[VT, KT]', '_fwdm_cls': 't.ClassVar[type[t.MutableMapping[t.Any, t.Any]]]', '_invm_cls': 't.ClassVar[type[t.MutableMapping[t.Any, t.Any]]]', '_inv_cls': 't.ClassVar[type[BidictBase[t.Any, t.Any]]]', '__reversed__': 't.ClassVar[t.Any]'}, '__doc__': 'Base class implementing :class:`BidirectionalMapping`.', 'on_dup': OnDup(key=OnDupAction.DROP_OLD, val=OnDupAction.RAISE), '_fwdm_cls': <class 'dict'>, '_invm_cls': <class 'dict'>, '__init_subclass__': <classmethod(<function BidictBase.__init_subclass__>)>, '_init_class': <classmethod(<function BidictBase._init_class>)>, '_set_reversed': <classmethod(<function BidictBase._set_reversed>)>, '_ensure_inv_cls': <classmethod(<function BidictBase._ensure_inv_cls>)>, '_make_inv_cls': <classmethod(<function BidictBase._make_inv_cls>)>, '_inv_cls_dict_diff': <classmethod(<function BidictBase._inv_cls_dict_diff>)>, '__init__': <function BidictBase.__init__>, 'inverse': <property object>, '_make_inverse': <function BidictBase._make_inverse>, 'inv': <property object>, '__repr__': <function BidictBase.__repr__>, 'values': <function BidictBase.values>, 'keys': <function BidictBase.keys>, 'items': <function BidictBase.items>, '__contains__': <function BidictBase.__contains__>, '__eq__': <function BidictBase.__eq__>, 'equals_order_sensitive': <function BidictBase.equals_order_sensitive>, '_dedup': <function BidictBase._dedup>, '_prep_write': <function BidictBase._prep_write>, '_update': <function BidictBase._update>, '_prep_writes': <function BidictBase._prep_writes>, '__copy__': <function BidictBase.__copy__>, 'copy': <function BidictBase.copy>, '_from_other': <staticmethod(<function BidictBase._from_other>)>, '_init_from': <function BidictBase._init_from>, '__or__': <function BidictBase.__or__>, '__ror__': <function BidictBase.__ror__>, '__len__': <function BidictBase.__len__>, '__iter__': <function BidictBase.__iter__>, '__getitem__': <function BidictBase.__getitem__>, '__reduce__': <function BidictBase.__reduce__>, '__orig_bases__': (bidict.BidirectionalMapping[~KT, ~VT],), '__dict__': <attribute '__dict__' of 'BidictBase' objects>, '__weakref__': <attribute '__weakref__' of 'BidictBase' objects>, '__hash__': None, '__parameters__': (~KT, ~VT), '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>, '_inv_cls': <class 'bidict.BidictBase'>, '__reversed__': <function _fwdm_reversed>})#
- __eq__(other)[source]#
x.__eq__(other) ⟺ x == other
Equivalent to dict(x.items()) == dict(other.items()) but more efficient.
Note that
bidict's __eq__()
implementation is inherited by subclasses, in particular by the ordered bidict subclasses, so even with ordered bidicts, == comparison is order-insensitive (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive).See also
equals_order_sensitive()
- __hash__ = None#
- __init__(arg=(), /, **kw)[source]#
Make a new bidirectional mapping. The signature behaves like that of
dict
. ktems passed via positional arg are processed first, followed by any items passed via keyword argument. Any duplication encountered along the way is handled as peron_dup
.
- __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()
- __module__ = 'bidict'#
- __or__(other)[source]#
Return self|other.
- Parameters:
self (BT) –
other (Mapping[KT, VT]) –
- Return type:
BT
- __orig_bases__ = (bidict.BidirectionalMapping[~KT, ~VT],)#
- __parameters__ = (~KT, ~VT)#
- __reversed__()#
Iterator over the contained keys in reverse order.
- Parameters:
self (BidictBase[KT, Any]) –
- Return type:
Iterator[KT]
- __ror__(other)[source]#
Return other|self.
- Parameters:
self (BT) –
other (Mapping[KT, VT]) –
- Return type:
BT
- __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)
- equals_order_sensitive(other)[source]#
Order-sensitive equality check.
See also __eq__() is order-insensitive (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive)
- get(k[, d]) D[k] if k in D, else d. d defaults to None. #
- property inv: BidictBase[VT, KT]#
Alias for
inverse
.
- property inverse: BidictBase[VT, KT]#
The inverse of this bidirectional mapping instance.
- items()[source]#
A set-like object providing a view on the contained items.
When b._fwdm is a
dict
, b.items() returns a dict_items object that behaves exactly the same as collections.abc.ItemsView(b), except for:offering better performance
being reversible on Python 3.8+
having a .mapping attribute in Python 3.10+ that exposes a mappingproxy to b._fwdm.
- Return type:
ItemsView[KT, VT]
- keys()[source]#
A set-like object providing a view on the contained keys.
When b._fwdm is a
dict
, b.keys() returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b), except foroffering better performance
being reversible on Python 3.8+
having a .mapping attribute in Python 3.10+ that exposes a mappingproxy to b._fwdm.
- Return type:
KeysView[KT]
- on_dup = (OnDupAction.DROP_OLD, OnDupAction.RAISE)#
- values()[source]#
A set-like object providing a view on the contained values.
Since the values of a bidict are equivalent to the keys of its inverse, this method returns a set-like object for this bidict’s values rather than just a collections.abc.ValuesView. This object supports set operations like union and difference, and constant- rather than linear-time containment checks, and is no more expensive to provide than the less capable collections.abc.ValuesView would be.
See
keys()
for more information.- Return type:
BidictKeysView[VT]
- class bidict.BidictKeysView(mapping)#
Bases:
KeysView
[KT
],ValuesView
[KT
]Since the keys of a bidict are the values of its inverse (and vice versa), the
ValuesView
result of calling bi.values() is also aKeysView
of bi.inverse.- __abstractmethods__ = frozenset({})#
- __and__(other)#
- __annotations__ = {}#
- classmethod __class_getitem__()#
Represent a PEP 585 generic type
E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
- __contains__(key)#
- __dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Since the keys of a bidict are the values of its inverse (and vice versa),\n the :class:`~collections.abc.ValuesView` result of calling *bi.values()*\n is also a :class:`~collections.abc.KeysView` of *bi.inverse*.\n ', '__orig_bases__': (typing.KeysView[~KT], typing.ValuesView[~KT]), '__dict__': <attribute '__dict__' of 'BidictKeysView' objects>, '__weakref__': <attribute '__weakref__' of 'BidictKeysView' objects>, '__parameters__': (~KT,), '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>, '__annotations__': {}})#
- __eq__(other)#
Return self==value.
- __ge__(other)#
Return self>=value.
- __gt__(other)#
Return self>value.
- __hash__ = None#
- __init__(mapping)#
- __init_subclass__()#
Function to initialize subclasses.
- __iter__()#
- __le__(other)#
Return self<=value.
- __len__()#
- __lt__(other)#
Return self<value.
- __module__ = 'bidict'#
- __or__(other)#
Return self|value.
- __orig_bases__ = (typing.KeysView[~KT], typing.ValuesView[~KT])#
- __parameters__ = (~KT,)#
- __rand__(other)#
- __repr__()#
Return repr(self).
- __ror__(other)#
Return value|self.
- __rsub__(other)#
- __rxor__(other)#
- __slots__ = ()#
- __sub__(other)#
- 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)
- __xor__(other)#
- isdisjoint(other)#
Return True if two sets have a null intersection.
- class bidict.GeneratedBidictInverse#
Bases:
object
Base class for dynamically-generated inverse bidict classes.
- __dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Base class for dynamically-generated inverse bidict classes.', '__dict__': <attribute '__dict__' of 'GeneratedBidictInverse' objects>, '__weakref__': <attribute '__weakref__' of 'GeneratedBidictInverse' objects>, '__annotations__': {}})#
- __module__ = 'bidict'#
- __weakref__#
list of weak references to the object (if defined)
- class bidict.MutableBidict(arg=(), /, **kw)#
Bases:
BidictBase
[KT
,VT
],MutableBidirectionalMapping
[KT
,VT
]Base class for mutable bidirectional mappings.
- Parameters:
arg (MapOrItems[KT, VT]) –
kw (VT) –
- __abstractmethods__ = frozenset({})#
- __annotations__ = {}#
- classmethod __class_getitem__()#
Represent a PEP 585 generic type
E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
- __contains__(key)#
True if the mapping contains the specified key, else False.
- __copy__()#
Used for the copy protocol. See the
copy
module.- Parameters:
self (BT) –
- Return type:
BT
- __dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Base class for mutable bidirectional mappings.', '_pop': <function MutableBidict._pop>, '__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>, 'putall': <function MutableBidict.putall>, '__ior__': <function MutableBidict.__ior__>, '__orig_bases__': (bidict.BidictBase[~KT, ~VT], bidict.MutableBidirectionalMapping[~KT, ~VT]), '__parameters__': (~KT, ~VT), '_inv_cls': <class 'bidict.MutableBidict'>, '__reversed__': <function _fwdm_reversed>, '__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 (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive).See also
equals_order_sensitive()
- __getitem__(key)#
x.__getitem__(key) ⟺ x[key]
- Parameters:
key (KT) –
- Return type:
VT
- __hash__ = None#
- __init__(arg=(), /, **kw)#
Make a new bidirectional mapping. The signature behaves like that of
dict
. ktems passed via positional arg are processed first, followed by any items passed via keyword argument. Any duplication encountered along the way is handled as peron_dup
.
- classmethod __init_subclass__()#
Function to initialize subclasses.
- Return type:
None
- __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()
- __ior__(other)[source]#
Return self|=other.
- Parameters:
other (Mapping[KT, VT]) –
- Return type:
MutableBidict[KT, VT]
- __module__ = 'bidict'#
- __orig_bases__ = (bidict.BidictBase[~KT, ~VT], bidict.MutableBidirectionalMapping[~KT, ~VT])#
- __parameters__ = (~KT, ~VT)#
- __reversed__()#
Iterator over the contained keys in reverse order.
- Parameters:
self (BidictBase[KT, Any]) –
- Return type:
Iterator[KT]
- __ror__(other)#
Return other|self.
- Parameters:
self (BT) –
other (Mapping[KT, VT]) –
- Return type:
BT
- __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 useforceput()
to unconditionally associate key with val, replacing any existing items as necessary to preserve uniqueness.- Raises:
bidict.ValueDuplicationError – if val duplicates that of an existing item.
bidict.KeyAndValueDuplicationError – if key duplicates the key of an existing item and val duplicates the value of a different existing item.
- Parameters:
key (KT) –
val (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)
- copy()#
Make a (shallow) copy of this bidict.
- Parameters:
self (BT) –
- Return type:
BT
- equals_order_sensitive(other)#
Order-sensitive equality check.
See also __eq__() is order-insensitive (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive)
- forceput(key, val)[source]#
Associate key with val unconditionally.
Replace any existing mappings containing key key or value val as necessary to preserve uniqueness.
- Parameters:
key (KT) –
val (VT) –
- Return type:
None
- forceupdate(arg=(), /, **kw)[source]#
Like a bulk
forceput()
.
- get(k[, d]) D[k] if k in D, else d. d defaults to None. #
- property inv: BidictBase[VT, KT]#
Alias for
inverse
.
- property inverse: BidictBase[VT, KT]#
The inverse of this bidirectional mapping instance.
- items()#
A set-like object providing a view on the contained items.
When b._fwdm is a
dict
, b.items() returns a dict_items object that behaves exactly the same as collections.abc.ItemsView(b), except for:offering better performance
being reversible on Python 3.8+
having a .mapping attribute in Python 3.10+ that exposes a mappingproxy to b._fwdm.
- Return type:
ItemsView[KT, VT]
- keys()#
A set-like object providing a view on the contained keys.
When b._fwdm is a
dict
, b.keys() returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b), except foroffering better performance
being reversible on Python 3.8+
having a .mapping attribute in Python 3.10+ that exposes a mappingproxy to b._fwdm.
- Return type:
KeysView[KT]
- on_dup = (OnDupAction.DROP_OLD, OnDupAction.RAISE)#
- pop(key, default=MissingT.MISSING, /)[source]#
x.pop(k[, d]) → v
Remove specified key and return the corresponding value.
- Raises:
KeyError – if key is not found and no default is provided.
- Parameters:
key (KT) –
default (DT | MissingT) –
- Return type:
VT | DT
- put(key, val, on_dup=(OnDupAction.RAISE, OnDupAction.RAISE))[source]#
Associate key with val, honoring the
OnDup
given in on_dup.For example, if on_dup is
ON_DUP_RAISE
, then key will be associated with val if and only if key is not already associated with an existing value and val is not already associated with an existing key, otherwise an exception will be raised.If key is already associated with val, this is a no-op.
- Raises:
bidict.KeyDuplicationError – if attempting to insert an item whose key only duplicates an existing item’s, and on_dup.key is
RAISE
.bidict.ValueDuplicationError – if attempting to insert an item whose value only duplicates an existing item’s, and on_dup.val is
RAISE
.bidict.KeyAndValueDuplicationError – if attempting to insert an item whose key duplicates one existing item’s, and whose value duplicates another existing item’s, and on_dup.val is
RAISE
.
- Parameters:
key (KT) –
val (VT) –
on_dup (OnDup) –
- Return type:
None
- putall(items, on_dup=(OnDupAction.RAISE, OnDupAction.RAISE))[source]#
Like a bulk
put()
.If one of the given items causes an exception to be raised, none of the items is inserted.
- setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D #
- 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 set-like object for this bidict’s values rather than just a collections.abc.ValuesView. This object supports set operations like union and difference, and constant- rather than linear-time containment checks, and is no more expensive to provide than the less capable collections.abc.ValuesView would be.
See
keys()
for more information.- Return type:
BidictKeysView[VT]
- class bidict.bidict(arg=(), /, **kw)#
Bases:
MutableBidict
[KT
,VT
]The main bidirectional mapping type.
See Introduction and Basic Usage to get started (also available at https://bidict.rtfd.io).
- Parameters:
arg (MapOrItems[KT, VT]) –
kw (VT) –
- __abstractmethods__ = frozenset({})#
- __annotations__ = {}#
- classmethod __class_getitem__()#
Represent a PEP 585 generic type
E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
- __contains__(key)#
True if the mapping contains the specified key, else False.
- __copy__()#
Used for the copy protocol. See the
copy
module.- Parameters:
self (BT) –
- Return type:
BT
- __delitem__(key)#
x.__delitem__(y) ⟺ del x[y]
- Parameters:
key (KT) –
- Return type:
None
- __dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'The main bidirectional mapping type.\n\n See :ref:`intro:Introduction` and :ref:`basic-usage:Basic Usage`\n to get started (also available at https://bidict.rtfd.io).\n ', '__orig_bases__': (bidict.MutableBidict[~KT, ~VT],), '__parameters__': (~KT, ~VT), '_inv_cls': <class 'bidict.bidict'>, '__reversed__': <function _fwdm_reversed>, '__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 (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive).See also
equals_order_sensitive()
- __getitem__(key)#
x.__getitem__(key) ⟺ x[key]
- Parameters:
key (KT) –
- Return type:
VT
- __hash__ = None#
- __init__(arg=(), /, **kw)#
Make a new bidirectional mapping. The signature behaves like that of
dict
. ktems passed via positional arg are processed first, followed by any items passed via keyword argument. Any duplication encountered along the way is handled as peron_dup
.
- classmethod __init_subclass__()#
Function to initialize subclasses.
- Return type:
None
- __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()
- __ior__(other)#
Return self|=other.
- Parameters:
other (Mapping[KT, VT]) –
- Return type:
MutableBidict[KT, VT]
- __module__ = 'bidict'#
- __orig_bases__ = (bidict.MutableBidict[~KT, ~VT],)#
- __parameters__ = (~KT, ~VT)#
- __reversed__()#
Iterator over the contained keys in reverse order.
- Parameters:
self (BidictBase[KT, Any]) –
- Return type:
Iterator[KT]
- __ror__(other)#
Return other|self.
- Parameters:
self (BT) –
other (Mapping[KT, VT]) –
- Return type:
BT
- __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 useforceput()
to unconditionally associate key with val, replacing any existing items as necessary to preserve uniqueness.- Raises:
bidict.ValueDuplicationError – if val duplicates that of an existing item.
bidict.KeyAndValueDuplicationError – if key duplicates the key of an existing item and val duplicates the value of a different existing item.
- Parameters:
key (KT) –
val (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)
- clear()#
Remove all items.
- Return type:
None
- copy()#
Make a (shallow) copy of this bidict.
- Parameters:
self (BT) –
- Return type:
BT
- equals_order_sensitive(other)#
Order-sensitive equality check.
See also __eq__() is order-insensitive (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive)
- 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 (KT) –
val (VT) –
- Return type:
None
- forceupdate(arg=(), /, **kw)#
Like a bulk
forceput()
.
- get(k[, d]) D[k] if k in D, else d. d defaults to None. #
- property inv: BidictBase[VT, KT]#
Alias for
inverse
.
- property inverse: BidictBase[VT, KT]#
The inverse of this bidirectional mapping instance.
- items()#
A set-like object providing a view on the contained items.
When b._fwdm is a
dict
, b.items() returns a dict_items object that behaves exactly the same as collections.abc.ItemsView(b), except for:offering better performance
being reversible on Python 3.8+
having a .mapping attribute in Python 3.10+ that exposes a mappingproxy to b._fwdm.
- Return type:
ItemsView[KT, VT]
- keys()#
A set-like object providing a view on the contained keys.
When b._fwdm is a
dict
, b.keys() returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b), except foroffering better performance
being reversible on Python 3.8+
having a .mapping attribute in Python 3.10+ that exposes a mappingproxy to b._fwdm.
- Return type:
KeysView[KT]
- on_dup = (OnDupAction.DROP_OLD, OnDupAction.RAISE)#
- pop(key, default=MissingT.MISSING, /)#
x.pop(k[, d]) → v
Remove specified key and return the corresponding value.
- Raises:
KeyError – if key is not found and no default is provided.
- Parameters:
key (KT) –
default (DT | MissingT) –
- Return type:
VT | DT
- popitem()#
x.popitem() → (k, v)
Remove and return some item as a (key, value) pair.
- put(key, val, on_dup=(OnDupAction.RAISE, OnDupAction.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:
bidict.KeyDuplicationError – if attempting to insert an item whose key only duplicates an existing item’s, and on_dup.key is
RAISE
.bidict.ValueDuplicationError – if attempting to insert an item whose value only duplicates an existing item’s, and on_dup.val is
RAISE
.bidict.KeyAndValueDuplicationError – if attempting to insert an item whose key duplicates one existing item’s, and whose value duplicates another existing item’s, and on_dup.val is
RAISE
.
- Parameters:
key (KT) –
val (VT) –
on_dup (OnDup) –
- Return type:
None
- putall(items, on_dup=(OnDupAction.RAISE, OnDupAction.RAISE))#
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 #
- 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 set-like object for this bidict’s values rather than just a collections.abc.ValuesView. This object supports set operations like union and difference, and constant- rather than linear-time containment checks, and is no more expensive to provide than the less capable collections.abc.ValuesView would be.
See
keys()
for more information.- Return type:
BidictKeysView[VT]
- class bidict.OnDup(key=OnDupAction.DROP_OLD, val=OnDupAction.RAISE)#
Bases:
NamedTuple
A combination of
OnDupAction
s specifying how to handle various types of duplication.The
key
field specifies what action to take when a duplicate key is encountered.The
val
field specifies what action to take when a duplicate value is encountered.In the case of both key and value duplication across two different items, only
val
is used.See also Values Must Be Unique (https://bidict.rtfd.io/basic-usage.html#values-must-be-unique)
- Parameters:
key (OnDupAction) –
val (OnDupAction) –
- __add__(value, /)#
Return self+value.
- __annotations__ = {'key': ForwardRef('OnDupAction'), 'val': ForwardRef('OnDupAction')}#
- __class_getitem__()#
See PEP 585
- __contains__(key, /)#
Return bool(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')#
- __module__ = 'bidict'#
- __mul__(value, /)#
Return self*value.
- __ne__(value, /)#
Return self!=value.
- static __new__(_cls, key=OnDupAction.DROP_OLD, val=OnDupAction.RAISE)#
Create new instance of OnDup(key, val)
- Parameters:
key (OnDupAction) –
val (OnDupAction) –
- __orig_bases__ = (<function NamedTuple>,)#
- __repr__()#
Return a nicely formatted representation string
- __rmul__(value, /)#
Return value*self.
- __slots__ = ()#
- 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: OnDupAction#
Alias for field number 0
- val: OnDupAction#
Alias for field number 1
- class bidict.OnDupAction(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)#
Bases:
Enum
An action to take to prevent duplication from occurring.
- RAISE = 'RAISE'#
- DROP_OLD = 'DROP_OLD'#
- DROP_NEW = 'DROP_NEW'#
- __module__ = 'bidict'#
- exception bidict.BidictException#
Bases:
Exception
Base class for bidict exceptions.
- __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)
- add_note()#
Exception.add_note(note) – add a note to the exception
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception bidict.DuplicationError#
Bases:
BidictException
Base class for exceptions raised when uniqueness is violated as per the
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)
- add_note()#
Exception.add_note(note) – add a note to the exception
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception bidict.KeyAndValueDuplicationError#
Bases:
KeyDuplicationError
,ValueDuplicationError
Raised when a given item’s key and value are not unique.
That is, its key duplicates that of another item, and its value duplicates that of a different other item.
- __annotations__ = {}#
- __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)
- add_note()#
Exception.add_note(note) – add a note to the exception
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception bidict.KeyDuplicationError#
Bases:
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)
- add_note()#
Exception.add_note(note) – add a note to the exception
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception bidict.ValueDuplicationError#
Bases:
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)
- add_note()#
Exception.add_note(note) – add a note to the exception
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class bidict.frozenbidict(arg=(), /, **kw)#
Bases:
BidictBase
[KT
,VT
]Immutable, hashable bidict type.
- Parameters:
arg (MapOrItems[KT, VT]) –
kw (VT) –
- __abstractmethods__ = frozenset({})#
- __annotations__ = {'_hash': 'int'}#
- classmethod __class_getitem__()#
Represent a PEP 585 generic type
E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
- __contains__(key)#
True if the mapping contains the specified key, else False.
- __copy__()#
Used for the copy protocol. See the
copy
module.- Parameters:
self (BT) –
- Return type:
BT
- __dict__ = mappingproxy({'__module__': 'bidict', '__annotations__': {'_hash': 'int'}, '__doc__': 'Immutable, hashable bidict type.', '__hash__': <function frozenbidict.__hash__>, '__orig_bases__': (bidict.BidictBase[~KT, ~VT],), '__parameters__': (~KT, ~VT), '_inv_cls': <class 'bidict.frozenbidict'>, '__reversed__': <function _fwdm_reversed>, '__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 (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive).See also
equals_order_sensitive()
- __getitem__(key)#
x.__getitem__(key) ⟺ x[key]
- Parameters:
key (KT) –
- Return type:
VT
- __init__(arg=(), /, **kw)#
Make a new bidirectional mapping. The signature behaves like that of
dict
. ktems passed via positional arg are processed first, followed by any items passed via keyword argument. Any duplication encountered along the way is handled as peron_dup
.
- classmethod __init_subclass__()#
Function to initialize subclasses.
- Return type:
None
- __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()
- __module__ = 'bidict'#
- __orig_bases__ = (bidict.BidictBase[~KT, ~VT],)#
- __parameters__ = (~KT, ~VT)#
- __reversed__()#
Iterator over the contained keys in reverse order.
- Parameters:
self (BidictBase[KT, Any]) –
- Return type:
Iterator[KT]
- __ror__(other)#
Return other|self.
- Parameters:
self (BT) –
other (Mapping[KT, VT]) –
- Return type:
BT
- __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)
- copy()#
Make a (shallow) copy of this bidict.
- Parameters:
self (BT) –
- Return type:
BT
- equals_order_sensitive(other)#
Order-sensitive equality check.
See also __eq__() is order-insensitive (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive)
- get(k[, d]) D[k] if k in D, else d. d defaults to None. #
- property inv: BidictBase[VT, KT]#
Alias for
inverse
.
- property inverse: BidictBase[VT, KT]#
The inverse of this bidirectional mapping instance.
- items()#
A set-like object providing a view on the contained items.
When b._fwdm is a
dict
, b.items() returns a dict_items object that behaves exactly the same as collections.abc.ItemsView(b), except for:offering better performance
being reversible on Python 3.8+
having a .mapping attribute in Python 3.10+ that exposes a mappingproxy to b._fwdm.
- Return type:
ItemsView[KT, VT]
- keys()#
A set-like object providing a view on the contained keys.
When b._fwdm is a
dict
, b.keys() returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b), except foroffering better performance
being reversible on Python 3.8+
having a .mapping attribute in Python 3.10+ that exposes a mappingproxy to b._fwdm.
- Return type:
KeysView[KT]
- on_dup = (OnDupAction.DROP_OLD, OnDupAction.RAISE)#
- values()#
A set-like object providing a view on the contained values.
Since the values of a bidict are equivalent to the keys of its inverse, this method returns a set-like object for this bidict’s values rather than just a collections.abc.ValuesView. This object supports set operations like union and difference, and constant- rather than linear-time containment checks, and is no more expensive to provide than the less capable collections.abc.ValuesView would be.
See
keys()
for more information.- Return type:
BidictKeysView[VT]
- 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.
- class bidict.OrderedBidictBase(arg=(), /, **kw)#
Bases:
BidictBase
[KT
,VT
]Base class implementing an ordered
BidirectionalMapping
.- Parameters:
arg (MapOrItems[KT, VT]) –
kw (VT) –
- __abstractmethods__ = frozenset({})#
- __annotations__ = {'_bykey': 'bool', '_node_by_korv': 'bidict[t.Any, Node]', '_ordered': 't.ClassVar[bool]'}#
- classmethod __class_getitem__()#
Represent a PEP 585 generic type
E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
- __contains__(key)#
True if the mapping contains the specified key, else False.
- __copy__()#
Used for the copy protocol. See the
copy
module.- Parameters:
self (BT) –
- Return type:
BT
- __dict__ = mappingproxy({'__module__': 'bidict', '__annotations__': {'_ordered': 't.ClassVar[bool]', '_node_by_korv': 'bidict[t.Any, Node]', '_bykey': 'bool'}, '__doc__': 'Base class implementing an ordered :class:`BidirectionalMapping`.', '_ordered': True, '__init__': <function OrderedBidictBase.__init__>, '_make_inverse': <function OrderedBidictBase._make_inverse>, '_assoc_node': <function OrderedBidictBase._assoc_node>, '_dissoc_node': <function OrderedBidictBase._dissoc_node>, '_init_from': <function OrderedBidictBase._init_from>, '_prep_write': <function OrderedBidictBase._prep_write>, '__iter__': <function OrderedBidictBase.__iter__>, '__reversed__': <function OrderedBidictBase.__reversed__>, '_iter': <function OrderedBidictBase._iter>, '__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 (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive).See also
equals_order_sensitive()
- __getitem__(key)#
x.__getitem__(key) ⟺ x[key]
- Parameters:
key (KT) –
- Return type:
VT
- __hash__ = None#
- __init__(arg=(), /, **kw)[source]#
Make a new ordered bidirectional mapping. The signature behaves like that of
dict
. Items passed in are added in the order they are passed, respecting theon_dup
class attribute in the process.The order in which items are inserted is remembered, similar to
collections.OrderedDict
.
- classmethod __init_subclass__()#
Function to initialize subclasses.
- Return type:
None
- __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()
- __module__ = 'bidict'#
- __orig_bases__ = (bidict.BidictBase[~KT, ~VT],)#
- __parameters__ = (~KT, ~VT)#
- __reversed__()[source]#
Iterator over the contained keys in reverse insertion order.
- Return type:
Iterator[KT]
- __ror__(other)#
Return other|self.
- Parameters:
self (BT) –
other (Mapping[KT, VT]) –
- Return type:
BT
- __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)
- copy()#
Make a (shallow) copy of this bidict.
- Parameters:
self (BT) –
- Return type:
BT
- equals_order_sensitive(other)#
Order-sensitive equality check.
See also __eq__() is order-insensitive (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive)
- get(k[, d]) D[k] if k in D, else d. d defaults to None. #
- property inv: BidictBase[VT, KT]#
Alias for
inverse
.
- property inverse: BidictBase[VT, KT]#
The inverse of this bidirectional mapping instance.
- items()#
A set-like object providing a view on the contained items.
When b._fwdm is a
dict
, b.items() returns a dict_items object that behaves exactly the same as collections.abc.ItemsView(b), except for:offering better performance
being reversible on Python 3.8+
having a .mapping attribute in Python 3.10+ that exposes a mappingproxy to b._fwdm.
- Return type:
ItemsView[KT, VT]
- keys()#
A set-like object providing a view on the contained keys.
When b._fwdm is a
dict
, b.keys() returns a dict_keys object that behaves exactly the same as collections.abc.KeysView(b), except foroffering better performance
being reversible on Python 3.8+
having a .mapping attribute in Python 3.10+ that exposes a mappingproxy to b._fwdm.
- Return type:
KeysView[KT]
- on_dup = (OnDupAction.DROP_OLD, OnDupAction.RAISE)#
- values()#
A set-like object providing a view on the contained values.
Since the values of a bidict are equivalent to the keys of its inverse, this method returns a set-like object for this bidict’s values rather than just a collections.abc.ValuesView. This object supports set operations like union and difference, and constant- rather than linear-time containment checks, and is no more expensive to provide than the less capable collections.abc.ValuesView would be.
See
keys()
for more information.- Return type:
BidictKeysView[VT]
- class bidict.OrderedBidict(arg=(), /, **kw)#
Bases:
OrderedBidictBase
[KT
,VT
],MutableBidict
[KT
,VT
]Mutable bidict type that maintains items in insertion order.
- Parameters:
arg (MapOrItems[KT, VT]) –
kw (VT) –
- __abstractmethods__ = frozenset({})#
- __annotations__ = {}#
- classmethod __class_getitem__()#
Represent a PEP 585 generic type
E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
- __contains__(key)#
True if the mapping contains the specified key, else False.
- __copy__()#
Used for the copy protocol. See the
copy
module.- Parameters:
self (BT) –
- Return type:
BT
- __delitem__(key)#
x.__delitem__(y) ⟺ del x[y]
- Parameters:
key (KT) –
- Return type:
None
- __dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Mutable bidict type that maintains items in insertion order.', 'clear': <function OrderedBidict.clear>, '_pop': <function OrderedBidict._pop>, 'popitem': <function OrderedBidict.popitem>, 'move_to_end': <function OrderedBidict.move_to_end>, 'keys': <function OrderedBidict.keys>, 'items': <function OrderedBidict.items>, '__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 (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive).See also
equals_order_sensitive()
- __getitem__(key)#
x.__getitem__(key) ⟺ x[key]
- Parameters:
key (KT) –
- Return type:
VT
- __hash__ = None#
- __init__(arg=(), /, **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 theon_dup
class attribute in the process.The order in which items are inserted is remembered, similar to
collections.OrderedDict
.
- classmethod __init_subclass__()#
Function to initialize subclasses.
- Return type:
None
- __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()
- __ior__(other)#
Return self|=other.
- Parameters:
other (Mapping[KT, VT]) –
- Return type:
MutableBidict[KT, VT]
- __module__ = 'bidict'#
- __orig_bases__ = (bidict.OrderedBidictBase[~KT, ~VT], bidict.MutableBidict[~KT, ~VT])#
- __parameters__ = (~KT, ~VT)#
- __reversed__()#
Iterator over the contained keys in reverse insertion order.
- Return type:
Iterator[KT]
- __ror__(other)#
Return other|self.
- Parameters:
self (BT) –
other (Mapping[KT, VT]) –
- Return type:
BT
- __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 useforceput()
to unconditionally associate key with val, replacing any existing items as necessary to preserve uniqueness.- Raises:
bidict.ValueDuplicationError – if val duplicates that of an existing item.
bidict.KeyAndValueDuplicationError – if key duplicates the key of an existing item and val duplicates the value of a different existing item.
- Parameters:
key (KT) –
val (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)
- copy()#
Make a (shallow) copy of this bidict.
- Parameters:
self (BT) –
- Return type:
BT
- equals_order_sensitive(other)#
Order-sensitive equality check.
See also __eq__() is order-insensitive (https://bidict.rtfd.io/other-bidict-types.html#eq-is-order-insensitive)
- 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 (KT) –
val (VT) –
- Return type:
None
- forceupdate(arg=(), /, **kw)#
Like a bulk
forceput()
.
- get(k[, d]) D[k] if k in D, else d. d defaults to None. #
- property inv: BidictBase[VT, KT]#
Alias for
inverse
.
- property inverse: BidictBase[VT, KT]#
The inverse of this bidirectional mapping instance.
- items()[source]#
A set-like object providing a view on the contained items.
- Return type:
ItemsView[KT, VT]
- move_to_end(key, last=True)[source]#
Move the item with the given key to the end if last is true, else to the beginning.
- on_dup = (OnDupAction.DROP_OLD, OnDupAction.RAISE)#
- pop(key, default=MissingT.MISSING, /)#
x.pop(k[, d]) → v
Remove specified key and return the corresponding value.
- Raises:
KeyError – if key is not found and no default is provided.
- Parameters:
key (KT) –
default (DT | MissingT) –
- Return type:
VT | DT
- popitem(last=True)[source]#
b.popitem() → (k, v)
If last is true, remove and return the most recently added item as a (key, value) pair. Otherwise, remove and return the least recently added item.
- put(key, val, on_dup=(OnDupAction.RAISE, OnDupAction.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:
bidict.KeyDuplicationError – if attempting to insert an item whose key only duplicates an existing item’s, and on_dup.key is
RAISE
.bidict.ValueDuplicationError – if attempting to insert an item whose value only duplicates an existing item’s, and on_dup.val is
RAISE
.bidict.KeyAndValueDuplicationError – if attempting to insert an item whose key duplicates one existing item’s, and whose value duplicates another existing item’s, and on_dup.val is
RAISE
.
- Parameters:
key (KT) –
val (VT) –
on_dup (OnDup) –
- Return type:
None
- putall(items, on_dup=(OnDupAction.RAISE, OnDupAction.RAISE))#
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 #
- 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 set-like object for this bidict’s values rather than just a collections.abc.ValuesView. This object supports set operations like union and difference, and constant- rather than linear-time containment checks, and is no more expensive to provide than the less capable collections.abc.ValuesView would be.
See
keys()
for more information.- Return type:
BidictKeysView[VT]
- bidict.RAISE = OnDupAction.RAISE#
An action to take to prevent duplication from occurring.
- bidict.DROP_OLD = OnDupAction.DROP_OLD#
An action to take to prevent duplication from occurring.
- bidict.DROP_NEW = OnDupAction.DROP_NEW#
An action to take to prevent duplication from occurring.
- bidict.ON_DUP_DEFAULT = (OnDupAction.DROP_OLD, OnDupAction.RAISE)#
A combination of
OnDupAction
s specifying how to handle various types of duplication.The
key
field specifies what action to take when a duplicate key is encountered.The
val
field specifies what action to take when a duplicate value is encountered.In the case of both key and value duplication across two different items, only
val
is used.See also Values Must Be Unique (https://bidict.rtfd.io/basic-usage.html#values-must-be-unique)
- bidict.ON_DUP_RAISE = (OnDupAction.RAISE, OnDupAction.RAISE)#
A combination of
OnDupAction
s specifying how to handle various types of duplication.The
key
field specifies what action to take when a duplicate key is encountered.The
val
field specifies what action to take when a duplicate value is encountered.In the case of both key and value duplication across two different items, only
val
is used.See also Values Must Be Unique (https://bidict.rtfd.io/basic-usage.html#values-must-be-unique)
- bidict.ON_DUP_DROP_OLD = (OnDupAction.DROP_OLD, OnDupAction.DROP_OLD)#
A combination of
OnDupAction
s specifying how to handle various types of duplication.The
key
field specifies what action to take when a duplicate key is encountered.The
val
field specifies what action to take when a duplicate value is encountered.In the case of both key and value duplication across two different items, only
val
is used.See also Values Must Be Unique (https://bidict.rtfd.io/basic-usage.html#values-must-be-unique)
- bidict.__version__#
The version of bidict represented as a string.