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 implementors 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#
- classmethod __init_subclass__(*args, **kwargs)#
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
- __inverted__()[source]#
Get an iterator over the items in
inverse
.This is functionally equivalent to iterating over the items in the forward mapping and inverting each one on the fly, but this provides a more efficient implementation: Assuming the already-inverted items are stored in
inverse
, just return an iterator over them directly.Providing this default implementation enables external functions, particularly
inverted()
, to use this optimized implementation when available, instead of having to invert on the fly.See also
bidict.inverted()
- 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#
- classmethod __init_subclass__(*args, **kwargs)#
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
- __inverted__()#
Get an iterator over the items in
inverse
.This is functionally equivalent to iterating over the items in the forward mapping and inverting each one on the fly, but this provides a more efficient implementation: Assuming the already-inverted items are stored in
inverse
, just return an iterator over them directly.Providing this default implementation enables external functions, particularly
inverted()
, to use this optimized implementation when available, instead of having to invert on the fly.See also
bidict.inverted()
- 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(*args, **kw)#
Bases:
BidirectionalMapping
[KT
,VT
]Base class implementing
BidirectionalMapping
.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- __abstractmethods__ = frozenset({})#
- __annotations__ = {'__reversed__': 't.Any', '_fwdm': 't.MutableMapping[KT, VT]', '_fwdm_cls': 't.ClassVar[t.Type[t.MutableMapping[t.Any, t.Any]]]', '_inv_cls': 't.ClassVar[t.Type[BidictBase[t.Any, t.Any]]]', '_invm': 't.MutableMapping[VT, KT]', '_invm_cls': 't.ClassVar[t.Type[t.MutableMapping[t.Any, t.Any]]]', '_repr_delegate': 't.ClassVar[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__()#
Make a (shallow) copy of this bidict.
- 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[t.Type[t.MutableMapping[t.Any, t.Any]]]', '_invm_cls': 't.ClassVar[t.Type[t.MutableMapping[t.Any, t.Any]]]', '_inv_cls': 't.ClassVar[t.Type[BidictBase[t.Any, t.Any]]]', '_repr_delegate': 't.ClassVar[t.Any]', '__reversed__': 't.Any'}, '__doc__': 'Base class implementing :class:`BidirectionalMapping`.', 'on_dup': OnDup(key=OD.DROP_OLD, val=OD.RAISE, kv=OD.RAISE), '_fwdm_cls': <class 'dict'>, '_invm_cls': <class 'dict'>, '_repr_delegate': <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>, 'copy': <function BidictBase.copy>, '_from_other': <staticmethod(<function BidictBase._from_other>)>, '_init_from': <function BidictBase._init_from>, '__copy__': <function BidictBase.copy>, '__or__': <function BidictBase.__or__>, '__ror__': <function BidictBase.__ror__>, '__len__': <function BidictBase.__len__>, '__iter__': <function BidictBase.__iter__>, '__getitem__': <function BidictBase.__getitem__>, '__reduce__': <function BidictBase.__reduce__>, '__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__(*args, **kw)[source]#
Make a new 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.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- classmethod __init_subclass__()[source]#
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend 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'#
- __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 = (OD.DROP_OLD, OD.RAISE, OD.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)#
- 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.
- __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(*args, **kw)#
Bases:
BidictBase
[KT
,VT
],MutableBidirectionalMapping
[KT
,VT
]Base class for mutable bidirectional mappings.
- Parameters:
args (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__()#
Make a (shallow) copy of this bidict.
- 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>, '__ior__': <function MutableBidict.__ior__>, 'putall': <function MutableBidict.putall>, '__orig_bases__': (bidict.BidictBase[~KT, ~VT], bidict.MutableBidirectionalMapping[~KT, ~VT]), '__parameters__': (~KT, ~VT), '_inv_cls': <class 'bidict.MutableBidict'>, '__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__(*args, **kw)#
Make a new 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.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- classmethod __init_subclass__()#
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend 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(*args, **kw)[source]#
Like a bulk
forceput()
.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- 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 = (OD.DROP_OLD, OD.RAISE, OD.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 (ODT[DT]) –
- Return type:
VT | DT
- put(key, val, on_dup=(OD.RAISE, OD.RAISE, OD.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.kv is
RAISE
.
- Parameters:
key (KT) –
val (VT) –
on_dup (OnDup) –
- Return type:
None
- putall(items, on_dup=(OD.RAISE, OD.RAISE, OD.RAISE))[source]#
Like a bulk
put()
.If one of the given items causes an exception to be raised, none of the items is inserted.
- Parameters:
items (MapOrItems[KT, VT]) –
on_dup (OnDup) –
- Return type:
None
- setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D #
- update(*args, **kw)[source]#
Like calling
putall()
with self.on_dup passed for on_dup.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- values()#
A set-like object providing a view on the contained values.
Since the values of a bidict are equivalent to the keys of its inverse, this method returns a 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(*args, **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:
args (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__()#
Make a (shallow) copy of this bidict.
- 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__(*args, **kw)#
Make a new 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.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- classmethod __init_subclass__()#
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend 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(*args, **kw)#
Like a bulk
forceput()
.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- 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 = (OD.DROP_OLD, OD.RAISE, OD.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 (ODT[DT]) –
- Return type:
VT | DT
- popitem()#
x.popitem() → (k, v)
Remove and return some item as a (key, value) pair.
- put(key, val, on_dup=(OD.RAISE, OD.RAISE, OD.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.kv is
RAISE
.
- Parameters:
key (KT) –
val (VT) –
on_dup (OnDup) –
- Return type:
None
- putall(items, on_dup=(OD.RAISE, OD.RAISE, OD.RAISE))#
Like a bulk
put()
.If one of the given items causes an exception to be raised, none of the items is inserted.
- Parameters:
items (MapOrItems[KT, VT]) –
on_dup (OnDup) –
- Return type:
None
- setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D #
- update(*args, **kw)#
Like calling
putall()
with self.on_dup passed for on_dup.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- values()#
A set-like object providing a view on the contained values.
Since the values of a bidict are equivalent to the keys of its inverse, this method returns a 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.OD(value, names=None, *, 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'#
- class bidict.OnDup(key=OD.DROP_OLD, val=OD.RAISE, kv=None)#
Bases:
_OnDup
A 3-tuple of
OD
s specifying how to handle the 3 kinds of duplication.See also Values Must Be Unique (https://bidict.rtfd.io/basic-usage.html#values-must-be-unique)
If kv is not specified, val will be used for kv.
- __add__(value, /)#
Return self+value.
- __annotations__ = {}#
- __class_getitem__()#
See PEP 585
- __contains__(key, /)#
Return key in self.
- __eq__(value, /)#
Return self==value.
- __ge__(value, /)#
Return self>=value.
- __getattribute__(name, /)#
Return getattr(self, name).
- __getitem__(key, /)#
Return self[key].
- __getnewargs__()#
Return self as a plain tuple. Used by copy and pickle.
- __gt__(value, /)#
Return self>value.
- __hash__()#
Return hash(self).
- __iter__()#
Implement iter(self).
- __le__(value, /)#
Return self<=value.
- __len__()#
Return len(self).
- __lt__(value, /)#
Return self<value.
- __match_args__ = ('key', 'val', 'kv')#
- __module__ = 'bidict'#
- __mul__(value, /)#
Return self*value.
- __ne__(value, /)#
Return self!=value.
- static __new__(cls, key=OD.DROP_OLD, val=OD.RAISE, kv=None)[source]#
Override to provide user-friendly default values.
- __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.
- 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 :attr:~bidict.RAISE`
OnDupAction
.- __annotations__ = {}#
- __cause__#
exception cause
- __context__#
exception context
- __delattr__(name, /)#
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Base class for exceptions raised when uniqueness is violated\n as per the :attr:~bidict.RAISE` :class:`~bidict.OnDupAction`.\n ', '__annotations__': {}})#
- __getattribute__(name, /)#
Return getattr(self, name).
- __init__(*args, **kwargs)#
- __module__ = 'bidict'#
- __new__(**kwargs)#
- __reduce__()#
Helper for pickle.
- __repr__()#
Return repr(self).
- __setattr__(name, value, /)#
Implement setattr(self, name, value).
- __setstate__()#
- __str__()#
Return str(self).
- __suppress_context__#
- __traceback__#
- __weakref__#
list of weak references to the object (if defined)
- 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(*args, **kw)#
Bases:
BidictBase
[KT
,VT
]Immutable, hashable bidict type.
- Parameters:
args (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__()#
Make a (shallow) copy of this bidict.
- 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__(*args, **kw)#
Make a new 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.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- classmethod __init_subclass__()#
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend 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 = (OD.DROP_OLD, OD.RAISE, OD.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.FrozenOrderedBidict(*args, **kw)#
Bases:
OrderedBidictBase
[KT
,VT
]Hashable, immutable, ordered bidict type.
Like a hashable
bidict.OrderedBidict
without the mutating APIs, or like a reversiblebidict.frozenbidict
even on Python < 3.8. (All bidicts are order-preserving when never mutated, so frozenbidict is already order-preserving, but only on Python 3.8+, where dicts are reversible, are all bidicts (including frozenbidict) also reversible.)If you are using Python 3.8+, frozenbidict gives you everything that FrozenOrderedBidict gives you, but with less space overhead. On the other hand, using FrozenOrderedBidict when you are depending on the ordering of the items can make the ordering dependence more explicit.
- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- __abstractmethods__ = frozenset({})#
- __annotations__ = {'__hash__': 't.Callable[[t.Any], 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__()#
Make a (shallow) copy of this bidict.
- Parameters:
self (BT) –
- Return type:
BT
- __dict__ = mappingproxy({'__module__': 'bidict', '__annotations__': {'__hash__': 't.Callable[[t.Any], int]'}, '__doc__': 'Hashable, immutable, ordered bidict type.\n\n Like a hashable :class:`bidict.OrderedBidict`\n without the mutating APIs, or like a\n reversible :class:`bidict.frozenbidict` even on Python < 3.8.\n (All bidicts are order-preserving when never mutated, so frozenbidict is\n already order-preserving, but only on Python 3.8+, where dicts are\n reversible, are all bidicts (including frozenbidict) also reversible.)\n\n If you are using Python 3.8+, frozenbidict gives you everything that\n FrozenOrderedBidict gives you, but with less space overhead.\n On the other hand, using FrozenOrderedBidict when you are depending on\n the ordering of the items can make the ordering dependence more explicit.\n ', '__hash__': <function frozenbidict.__hash__>, '__orig_bases__': (bidict.OrderedBidictBase[~KT, ~VT],), '__parameters__': (~KT, ~VT), '_inv_cls': <class 'bidict.FrozenOrderedBidict'>, '__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__(*args, **kw)#
Make a new ordered bidirectional mapping. The signature behaves like that of
dict
. Items passed in are added in the order they are passed, respecting theon_dup
class attribute in the process.The order in which items are inserted is remembered, similar to
collections.OrderedDict
.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- classmethod __init_subclass__()#
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend 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.OrderedBidictBase[~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
- __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 = (OD.DROP_OLD, OD.RAISE, OD.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.
See also
bidict.BidirectionalMapping.__inverted__
- Parameters:
arg (MapOrItems[KT, VT]) –
- Return type:
ItemsIter[VT, KT]
- class bidict.NamedBidictBase#
Bases:
object
Base class that namedbidicts derive from.
- __dict__ = mappingproxy({'__module__': 'bidict', '__doc__': 'Base class that namedbidicts derive from.', '__dict__': <attribute '__dict__' of 'NamedBidictBase' objects>, '__weakref__': <attribute '__weakref__' of 'NamedBidictBase' objects>, '__annotations__': {}})#
- __module__ = 'bidict'#
- __weakref__#
list of weak references to the object (if defined)
- bidict.namedbidict(typename, keyname, valname, *, base_type=<class 'bidict.bidict'>)#
Create a new subclass of base_type with custom accessors.
Like
collections.namedtuple()
for bidicts.The new class’s
__name__
and__qualname__
will be set to typename, and its__module__
will be set to the caller’s module.Instances of the new class will provide access to their
inverse
instances via the custom keyname_for property, and access to themselves via the custom valname_for property.See also the namedbidict usage documentation (https://bidict.rtfd.io/other-bidict-types.html#namedbidict)
- Raises:
ValueError – if any of the typename, keyname, or valname strings is not a valid Python identifier, or if keyname == valname.
TypeError – if base_type is not a
bidict.BidictBase
subclass. Any of the concrete bidict types pictured in the Bidict Types Diagram may be provided (https://bidict.rtfd.io/other-bidict-types.html#bidict-types-diagram).
- Parameters:
typename (str) –
keyname (str) –
valname (str) –
base_type (Type[BidictBase[KT, VT]]) –
- Return type:
Type[BidictBase[KT, VT]]
- class bidict.OrderedBidictBase(*args, **kw)#
Bases:
BidictBase
[KT
,VT
]Base class implementing an ordered
BidirectionalMapping
.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- __abstractmethods__ = frozenset({})#
- __annotations__ = {'_bykey': 'bool', '_node_by_korv': 'bidict[t.Any, Node]', '_repr_delegate': 't.ClassVar[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,).
- __contains__(key)#
True if the mapping contains the specified key, else False.
- __copy__()#
Make a (shallow) copy of this bidict.
- Parameters:
self (BT) –
- Return type:
BT
- __dict__ = mappingproxy({'__module__': 'bidict', '__annotations__': {'_repr_delegate': 't.ClassVar[t.Any]', '_node_by_korv': 'bidict[t.Any, Node]', '_bykey': 'bool'}, '__doc__': 'Base class implementing an ordered :class:`BidirectionalMapping`.', '_repr_delegate': <class 'list'>, '__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__(*args, **kw)[source]#
Make a new ordered bidirectional mapping. The signature behaves like that of
dict
. Items passed in are added in the order they are passed, respecting theon_dup
class attribute in the process.The order in which items are inserted is remembered, similar to
collections.OrderedDict
.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- classmethod __init_subclass__()#
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend 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 = (OD.DROP_OLD, OD.RAISE, OD.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(*args, **kw)#
Bases:
OrderedBidictBase
[KT
,VT
],MutableBidict
[KT
,VT
]Mutable bidict type that maintains items in insertion order.
- Parameters:
args (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__()#
Make a (shallow) copy of this bidict.
- 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__(*args, **kw)#
Make a new ordered bidirectional mapping. The signature behaves like that of
dict
. Items passed in are added in the order they are passed, respecting theon_dup
class attribute in the process.The order in which items are inserted is remembered, similar to
collections.OrderedDict
.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- classmethod __init_subclass__()#
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend 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(*args, **kw)#
Like a bulk
forceput()
.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- 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 = (OD.DROP_OLD, OD.RAISE, OD.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 (ODT[DT]) –
- 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=(OD.RAISE, OD.RAISE, OD.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.kv is
RAISE
.
- Parameters:
key (KT) –
val (VT) –
on_dup (OnDup) –
- Return type:
None
- putall(items, on_dup=(OD.RAISE, OD.RAISE, OD.RAISE))#
Like a bulk
put()
.If one of the given items causes an exception to be raised, none of the items is inserted.
- Parameters:
items (MapOrItems[KT, VT]) –
on_dup (OnDup) –
- Return type:
None
- setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D #
- update(*args, **kw)#
Like calling
putall()
with self.on_dup passed for on_dup.- Parameters:
args (MapOrItems[KT, VT]) –
kw (VT) –
- Return type:
None
- values()#
A set-like object providing a view on the contained values.
Since the values of a bidict are equivalent to the keys of its inverse, this method returns a 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.OnDupAction#
Alias
- bidict.RAISE = OD.RAISE#
An action to take to prevent duplication from occurring.
- bidict.DROP_OLD = OD.DROP_OLD#
An action to take to prevent duplication from occurring.
- bidict.DROP_NEW = OD.DROP_NEW#
An action to take to prevent duplication from occurring.
- bidict.ON_DUP_DEFAULT = (OD.DROP_OLD, OD.RAISE, OD.RAISE)#
A 3-tuple of
OD
s specifying how to handle the 3 kinds of duplication.See also Values Must Be Unique (https://bidict.rtfd.io/basic-usage.html#values-must-be-unique)
If kv is not specified, val will be used for kv.
- bidict.ON_DUP_RAISE = (OD.RAISE, OD.RAISE, OD.RAISE)#
A 3-tuple of
OD
s specifying how to handle the 3 kinds of duplication.See also Values Must Be Unique (https://bidict.rtfd.io/basic-usage.html#values-must-be-unique)
If kv is not specified, val will be used for kv.
- bidict.ON_DUP_DROP_OLD = (OD.DROP_OLD, OD.DROP_OLD, OD.DROP_OLD)#
A 3-tuple of
OD
s specifying how to handle the 3 kinds of duplication.See also Values Must Be Unique (https://bidict.rtfd.io/basic-usage.html#values-must-be-unique)
If kv is not specified, val will be used for kv.
- bidict.__version__#
The version of bidict represented as a string.