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[source]

Bases: collections.abc.Mapping

Abstract base class (ABC) for bidirectional mapping types.

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

__slots__ = ()
abstract property inverse

The inverse of this bidirectional mapping instance.

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

Raises

NotImplementedError – Meant to be overridden in 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()

values()[source]

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

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

__class__

alias of abc.ABCMeta

__contains__(key)
__delattr__()

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__(other)

Return self==value.

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

abstract __getitem__(key)
__gt__()

Return self>value.

__hash__ = None
__init__()

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

__init_subclass__()

This method is called when a class is subclassed.

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

abstract __iter__()
__le__()

Return self<=value.

abstract __len__()
__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return repr(self).

__reversed__ = None
__setattr__()

Implement setattr(self, name, value).

__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

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

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
class bidict.BidictBase(*args, **kw)[source]

Bases: bidict._abc.BidirectionalMapping

Base class implementing BidirectionalMapping.

__slots__ = ('_fwdm', '_invm', '_inv', '_invweak', '_hash', '__weakref__')
on_dup = OnDup(key=<bidict.DROP_OLD>, val=<bidict.RAISE>, kv=<bidict.RAISE>)

The default OnDup that governs behavior when a provided item duplicates the key or value of other item(s).

See also Values Must Be Unique, Extending bidict

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

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

property inverse

The inverse of this bidict.

See also inv

property inv

Alias for inverse.

__getstate__()[source]

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

See also object.__getstate__()

__setstate__(state)[source]

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__repr__()[source]

See repr().

__eq__(other)[source]

x.__eq__(other) ⟺ x == other

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

Note that bidict's __eq__() implementation is inherited by subclasses, in particular by the ordered bidict subclasses, so even with ordered bidicts, == comparison is order-insensitive.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

copy()[source]

A shallow copy.

__copy__()[source]

Used for the copy protocol.

See also the copy module

__len__()[source]

The number of contained items.

__iter__()[source]

Iterator over the contained keys.

__getitem__(key)[source]

x.__getitem__(key) ⟺ x[key]

__class__

alias of abc.ABCMeta

__contains__(key)
__delattr__()

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__gt__()

Return self>value.

__hash__ = None
__init_subclass__()

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

__le__()

Return self<=value.

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__reversed__ = None
__setattr__()

Implement setattr(self, name, value).

__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

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

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

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

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

class bidict.MutableBidict(*args, **kw)[source]

Bases: bidict._base.BidictBase, collections.abc.MutableMapping

Base class for mutable bidirectional mappings.

__slots__ = ()
__delitem__(key)[source]

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

__setitem__(key, val)[source]

Set the value for key to val.

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

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

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

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

Raises
put(key, val, on_dup=OnDup(key=<bidict.RAISE>, val=<bidict.RAISE>, kv=<bidict.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
forceput(key, val)[source]

Associate key with val unconditionally.

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

clear()[source]

Remove all items.

pop(key, default=<MISS>)[source]

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

Remove specified key and return the corresponding value.

Raises

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

popitem()[source]

x.popitem() → (k, v)

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

Raises

KeyError – if x is empty.

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

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

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

Like a bulk forceput().

putall(items, on_dup=OnDup(key=<bidict.RAISE>, val=<bidict.RAISE>, kv=<bidict.RAISE>))[source]

Like a bulk put().

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

__class__

alias of abc.ABCMeta

__contains__(key)
__copy__()

Used for the copy protocol.

See also the copy module

__delattr__()

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__(other)

x.__eq__(other) ⟺ x == other

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

Note that bidict's __eq__() implementation is inherited by subclasses, in particular by the ordered bidict subclasses, so even with ordered bidicts, == comparison is order-insensitive.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__getitem__(key)

x.__getitem__(key) ⟺ x[key]

__getstate__()

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

See also object.__getstate__()

__gt__()

Return self>value.

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

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

__init_subclass__()

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

__iter__()

Iterator over the contained keys.

__le__()

Return self<=value.

__len__()

The number of contained items.

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

See repr().

__reversed__ = None
__setattr__()

Implement setattr(self, name, value).

__setstate__(state)

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

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

copy()

A shallow copy.

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

Alias for inverse.

property inverse

The inverse of this bidict.

See also inv

items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
on_dup = OnDup(key=<bidict.DROP_OLD>, val=<bidict.RAISE>, kv=<bidict.RAISE>)
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.

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

class bidict.bidict(*args, **kw)[source]

Bases: bidict._delegating._DelegatingMixin, bidict._mut.MutableBidict

Base class for mutable bidirectional mappings.

__slots__ = ()
__class__

alias of abc.ABCMeta

__contains__(key)
__copy__()

Used for the copy protocol.

See also the copy module

__delattr__()

Implement delattr(self, name).

__delitem__(key)

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

__dir__()

Default dir() implementation.

__eq__(other)

x.__eq__(other) ⟺ x == other

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

Note that bidict's __eq__() implementation is inherited by subclasses, in particular by the ordered bidict subclasses, so even with ordered bidicts, == comparison is order-insensitive.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__getitem__(key)

x.__getitem__(key) ⟺ x[key]

__getstate__()

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

See also object.__getstate__()

__gt__()

Return self>value.

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

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

__init_subclass__()

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

__iter__()

Iterator over the contained keys.

__le__()

Return self<=value.

__len__()

The number of contained items.

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

See repr().

__reversed__ = None
__setattr__()

Implement setattr(self, name, value).

__setitem__(key, val)

Set the value for key to val.

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

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

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

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

Raises
__setstate__(state)

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

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

clear()

Remove all items.

copy()

A shallow copy.

forceput(key, val)

Associate key with val unconditionally.

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

forceupdate(*args, **kw)

Like a bulk forceput().

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

Alias for inverse.

property inverse

The inverse of this bidict.

See also inv

items()

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

keys()

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

on_dup = OnDup(key=<bidict.DROP_OLD>, val=<bidict.RAISE>, kv=<bidict.RAISE>)
pop(key, default=<MISS>)

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

Remove specified key and return the corresponding value.

Raises

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

popitem()

x.popitem() → (k, v)

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

Raises

KeyError – if x is empty.

put(key, val, on_dup=OnDup(key=<bidict.RAISE>, val=<bidict.RAISE>, kv=<bidict.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
putall(items, on_dup=OnDup(key=<bidict.RAISE>, val=<bidict.RAISE>, kv=<bidict.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
update(*args, **kw)

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

values()

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

class bidict.frozenbidict(*args, **kw)[source]

Bases: bidict._delegating._DelegatingMixin, bidict._base.BidictBase

Immutable, hashable bidict type.

__slots__ = ()
__hash__()[source]

The hash of this bidict as determined by its items.

__class__

alias of abc.ABCMeta

__contains__(key)
__copy__()

Used for the copy protocol.

See also the copy module

__delattr__()

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__(other)

x.__eq__(other) ⟺ x == other

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

Note that bidict's __eq__() implementation is inherited by subclasses, in particular by the ordered bidict subclasses, so even with ordered bidicts, == comparison is order-insensitive.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__getitem__(key)

x.__getitem__(key) ⟺ x[key]

__getstate__()

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

See also object.__getstate__()

__gt__()

Return self>value.

__init__(*args, **kw)

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

__init_subclass__()

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

__iter__()

Iterator over the contained keys.

__le__()

Return self<=value.

__len__()

The number of contained items.

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

See repr().

__reversed__ = None
__setattr__()

Implement setattr(self, name, value).

__setstate__(state)

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

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

copy()

A shallow copy.

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

Alias for inverse.

property inverse

The inverse of this bidict.

See also inv

items()

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

keys()

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

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

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

class bidict.FrozenOrderedBidict(*args, **kw)[source]

Bases: bidict._orderedbase.OrderedBidictBase

Hashable, immutable, ordered bidict type.

__slots__ = ()
__hash__()

The hash of this bidict as determined by its items.

__iter__(reverse=False)[source]

Iterator over the contained keys in insertion order.

keys()[source]

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

values()[source]

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

__class__

alias of abc.ABCMeta

__contains__(key)
__copy__()

Used for the copy protocol.

See also the copy module

__delattr__()

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__(other)

x.__eq__(other) ⟺ x == other

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

Note that bidict's __eq__() implementation is inherited by subclasses, in particular by the ordered bidict subclasses, so even with ordered bidicts, == comparison is order-insensitive.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__getitem__(key)

x.__getitem__(key) ⟺ x[key]

__getstate__()

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

See also object.__getstate__()

__gt__()

Return self>value.

__init__(*args, **kw)

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

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

__init_subclass__()

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

__le__()

Return self<=value.

__len__()

The number of contained items.

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

See repr().

__reversed__()

Iterator over the contained keys in reverse insertion order.

__setattr__()

Implement setattr(self, name, value).

__setstate__(state)

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

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

copy()

A shallow copy of this ordered bidict.

equals_order_sensitive(other)

Order-sensitive equality check.

See also __eq__() is order-insensitive

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

Alias for inverse.

property inverse

The inverse of this bidict.

See also inv

items() → a set-like object providing a view on D's items
on_dup = OnDup(key=<bidict.DROP_OLD>, val=<bidict.RAISE>, kv=<bidict.RAISE>)
bidict.namedbidict(typename, keyname, valname, base_type=<class 'bidict._bidict.bidict'>)[source]

Create a new subclass of base_type with custom accessors.

Analagous to collections.namedtuple().

The new class’s __name__ and __qualname__ will be set based on typename.

Instances of it will provide access to their inverses via the custom keyname_for property, and access to themselves via the custom valname_for property.

See also the namedbidict usage documentation

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

  • TypeError – if base_type is not a subclass of BidirectionalMapping. (This function requires slightly more of base_type, e.g. the availability of an _isinv attribute, but all the concrete bidict types that the bidict module provides can be passed in. Check out the code if you actually need to pass in something else.)

class bidict.OrderedBidictBase(*args, **kw)[source]

Bases: bidict._base.BidictBase

Base class implementing an ordered BidirectionalMapping.

__slots__ = ('_sntl',)
__init__(*args, **kw)[source]

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

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

copy()[source]

A shallow copy of this ordered bidict.

__getitem__(key)[source]

x.__getitem__(key) ⟺ x[key]

__iter__(reverse=False)[source]

Iterator over the contained keys in insertion order.

__reversed__()[source]

Iterator over the contained keys in reverse insertion order.

equals_order_sensitive(other)[source]

Order-sensitive equality check.

See also __eq__() is order-insensitive

__class__

alias of abc.ABCMeta

__contains__(key)
__copy__()

Used for the copy protocol.

See also the copy module

__delattr__()

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__(other)

x.__eq__(other) ⟺ x == other

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

Note that bidict's __eq__() implementation is inherited by subclasses, in particular by the ordered bidict subclasses, so even with ordered bidicts, == comparison is order-insensitive.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__getstate__()

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

See also object.__getstate__()

__gt__()

Return self>value.

__hash__ = None
__init_subclass__()

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

__le__()

Return self<=value.

__len__()

The number of contained items.

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

See repr().

__setattr__()

Implement setattr(self, name, value).

__setstate__(state)

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

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

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

Alias for inverse.

property inverse

The inverse of this bidict.

See also inv

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

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

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

class bidict.OrderedBidict(*args, **kw)[source]

Bases: bidict._orderedbase.OrderedBidictBase, bidict._mut.MutableBidict

Mutable bidict type that maintains items in insertion order.

__slots__ = ()
clear()[source]

Remove all items.

popitem(last=True)[source]

x.popitem() → (k, v)

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

Raises

KeyError – if x is empty.

move_to_end(key, last=True)[source]

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

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

Raises

KeyError – if the key does not exist

__class__

alias of abc.ABCMeta

__contains__(key)
__copy__()

Used for the copy protocol.

See also the copy module

__delattr__()

Implement delattr(self, name).

__delitem__(key)

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

__dir__()

Default dir() implementation.

__eq__(other)

x.__eq__(other) ⟺ x == other

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

Note that bidict's __eq__() implementation is inherited by subclasses, in particular by the ordered bidict subclasses, so even with ordered bidicts, == comparison is order-insensitive.

See also bidict.FrozenOrderedBidict.equals_order_sensitive()

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__getitem__(key)

x.__getitem__(key) ⟺ x[key]

__getstate__()

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

See also object.__getstate__()

__gt__()

Return self>value.

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

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

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

__init_subclass__()

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

__iter__(reverse=False)

Iterator over the contained keys in insertion order.

__le__()

Return self<=value.

__len__()

The number of contained items.

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

See repr().

__reversed__()

Iterator over the contained keys in reverse insertion order.

__setattr__()

Implement setattr(self, name, value).

__setitem__(key, val)

Set the value for key to val.

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

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

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

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

Raises
__setstate__(state)

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

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

copy()

A shallow copy of this ordered bidict.

equals_order_sensitive(other)

Order-sensitive equality check.

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

forceupdate(*args, **kw)

Like a bulk forceput().

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

Alias for inverse.

property inverse

The inverse of this bidict.

See also inv

items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
on_dup = OnDup(key=<bidict.DROP_OLD>, val=<bidict.RAISE>, kv=<bidict.RAISE>)
pop(key, default=<MISS>)

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.

put(key, val, on_dup=OnDup(key=<bidict.RAISE>, val=<bidict.RAISE>, kv=<bidict.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
putall(items, on_dup=OnDup(key=<bidict.RAISE>, val=<bidict.RAISE>, kv=<bidict.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
update(*args, **kw)

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

values()

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

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

class bidict.OnDup[source]

Bases: bidict._dup._OnDup

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

See also Values Must Be Unique

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

__slots__ = ()
static __new__(cls, key=<bidict.DROP_OLD>, val=<bidict.RAISE>, kv=<bidict.RAISE>)[source]

Override to provide user-friendly default values.

__add__()

Return self+value.

__class__

alias of builtins.type

__contains__()

Return key in self.

__delattr__()

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__()

Return self==value.

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__getitem__()

Return self[key].

__getnewargs__()

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

__gt__()

Return self>value.

__hash__()

Return hash(self).

__init__()

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

__init_subclass__()

This method is called when a class is subclassed.

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

__iter__()

Implement iter(self).

__le__()

Return self<=value.

__len__()

Return len(self).

__lt__()

Return self<value.

__mul__()

Return self*value.

__ne__()

Return self!=value.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return a nicely formatted representation string

__rmul__()

Return value*self.

__setattr__()

Implement setattr(self, name, value).

__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

__subclasshook__()

Abstract classes can override this to customize issubclass().

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

count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

property key

Alias for field number 0

property kv

Alias for field number 2

property val

Alias for field number 1

class bidict.OnDupAction[source]

Bases: enum.Enum

An action to take to prevent duplication from occurring.

RAISE = 'RAISE'

Raise a DuplicationError.

DROP_OLD = 'DROP_OLD'

Overwrite existing items with new items.

DROP_NEW = 'DROP_NEW'

Keep existing items and drop new items.

__class__

alias of enum.EnumMeta

__members__ = mappingproxy(OrderedDict([('RAISE', <bidict.RAISE>), ('DROP_OLD', <bidict.DROP_OLD>), ('DROP_NEW', <bidict.DROP_NEW>)]))
exception bidict.BidictException[source]

Bases: Exception

Base class for bidict exceptions.

__cause__

exception cause

__class__

alias of builtins.type

__context__

exception context

__delattr__()

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__()

Return self==value.

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__gt__()

Return self>value.

__hash__()

Return hash(self).

__init__()

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

__init_subclass__()

This method is called when a class is subclassed.

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

__le__()

Return self<=value.

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__()

Implement setattr(self, name, value).

__setstate__()
__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

__subclasshook__()

Abstract classes can override this to customize issubclass().

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

__suppress_context__
__traceback__
args
with_traceback()

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

exception bidict.DuplicationError[source]

Bases: bidict._exc.BidictException

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

__cause__

exception cause

__class__

alias of builtins.type

__context__

exception context

__delattr__()

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__()

Return self==value.

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__gt__()

Return self>value.

__hash__()

Return hash(self).

__init__()

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

__init_subclass__()

This method is called when a class is subclassed.

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

__le__()

Return self<=value.

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__()

Implement setattr(self, name, value).

__setstate__()
__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

__subclasshook__()

Abstract classes can override this to customize issubclass().

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

__suppress_context__
__traceback__
args
with_traceback()

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

exception bidict.KeyDuplicationError[source]

Bases: bidict._exc.DuplicationError

Raised when a given key is not unique.

__cause__

exception cause

__class__

alias of builtins.type

__context__

exception context

__delattr__()

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__()

Return self==value.

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__gt__()

Return self>value.

__hash__()

Return hash(self).

__init__()

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

__init_subclass__()

This method is called when a class is subclassed.

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

__le__()

Return self<=value.

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__()

Implement setattr(self, name, value).

__setstate__()
__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

__subclasshook__()

Abstract classes can override this to customize issubclass().

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

__suppress_context__
__traceback__
args
with_traceback()

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

exception bidict.ValueDuplicationError[source]

Bases: bidict._exc.DuplicationError

Raised when a given value is not unique.

__cause__

exception cause

__class__

alias of builtins.type

__context__

exception context

__delattr__()

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__()

Return self==value.

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__gt__()

Return self>value.

__hash__()

Return hash(self).

__init__()

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

__init_subclass__()

This method is called when a class is subclassed.

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

__le__()

Return self<=value.

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__()

Implement setattr(self, name, value).

__setstate__()
__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

__subclasshook__()

Abstract classes can override this to customize issubclass().

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

__suppress_context__
__traceback__
args
with_traceback()

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

exception bidict.KeyAndValueDuplicationError[source]

Bases: bidict._exc.KeyDuplicationError, bidict._exc.ValueDuplicationError

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

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

__cause__

exception cause

__class__

alias of builtins.type

__context__

exception context

__delattr__()

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__()

Return self==value.

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__gt__()

Return self>value.

__hash__()

Return hash(self).

__init__()

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

__init_subclass__()

This method is called when a class is subclassed.

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

__le__()

Return self<=value.

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

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

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__()

Implement setattr(self, name, value).

__setstate__()
__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

__subclasshook__()

Abstract classes can override this to customize issubclass().

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

__suppress_context__
__traceback__
args
with_traceback()

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

bidict.inverted(arg)[source]

Yield the inverse items of the provided object.

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

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

See also bidict.BidirectionalMapping.__inverted__

bidict.RAISE = <bidict.RAISE>

An action to take to prevent duplication from occurring.

bidict.DROP_OLD = <bidict.DROP_OLD>

An action to take to prevent duplication from occurring.

bidict.DROP_NEW = <bidict.DROP_NEW>

An action to take to prevent duplication from occurring.

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

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

See also Values Must Be Unique

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

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

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

See also Values Must Be Unique

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

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

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

See also Values Must Be Unique

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

bidict._util._iteritems_mapping_or_iterable(arg)[source]

Yield the items in arg.

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

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

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

Raises

TypeError – if more than one positional argument is given.

bidict.__version__

The version of bidict represented as a string.

bidict.__version_info__

The version of bidict represented as a tuple.

bidict.compat

Compatibility helpers.

bidict.compat.PYMAJOR = 3
bidict.compat.PYMINOR = 7
bidict.compat.PY2 = False
bidict.compat.PYIMPL = 'CPython'
bidict.compat.CPY = True
bidict.compat.PYPY = False
bidict.compat.DICTS_ORDERED = True