API

This page contains auto-generated documentation from the bidict source code.

bidict

Efficient, Pythonic bidirectional map implementation and related functionality.

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

__class__

alias of abc.ABCMeta

__contains__(key)
__delattr__()

Implement delattr(self, name).

__dir__() → list

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__() → int

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() → an object providing a view on D's values
class bidict.BidictBase(*args, **kw)[source]

Bases: bidict._abc.BidirectionalMapping

Base class implementing BidirectionalMapping.

__slots__ = ('_fwdm', '_invm', '_inv', '_invweak', '_hash', '__weakref__')
on_dup_key = <DUP_POLICY.OVERWRITE>

The default DuplicationPolicy (in effect during e.g. __init__() calls) that governs behavior when a provided item duplicates only the key of another item.

Defaults to OVERWRITE to match dict’s behavior.

See also Values Must Be Unique, Extending bidict

on_dup_val = <DUP_POLICY.RAISE>

The default DuplicationPolicy (in effect during e.g. __init__() calls) that governs behavior when a provided item duplicates only the value of another item.

Defaults to RAISE to prevent unintended overwrite of another item.

See also Values Must Be Unique, Extending bidict

on_dup_kv = None

The default DuplicationPolicy (in effect during e.g. __init__() calls) that governs behavior when a provided item duplicates the key of another item and the value of a third item.

Defaults to None, which causes the on_dup_kv policy to match whatever on_dup_val policy is in effect.

See also Values Must Be Unique, Extending bidict

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

Make a new bidirectional dictionary. The signature is the same as that of regular dictionaries. Items passed in are added in the order they are passed, respecting the current duplication policies in the process.

See also on_dup_key, on_dup_val, on_dup_kv

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

__getitem__(key)[source]

x.__getitem__(key) ⟺ x[key]

values()[source]

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

Note that 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.

__ne__()

Return self!=value.

__class__

alias of abc.ABCMeta

__contains__(key)
__delattr__()

Implement delattr(self, name).

__dir__() → list

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.

__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__() → int

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.MutableBidict(*args, **kw)[source]

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

Base class for mutable bidirectional mappings.

__slots__ = ()
__hash__ = None
__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 policy 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_key=<DUP_POLICY.RAISE>, on_dup_val=<DUP_POLICY.RAISE>, on_dup_kv=None)[source]

Associate key with val with the specified duplication policies.

If on_dup_kv is None, the on_dup_val policy will be used for it.

For example, if all given duplication policies are 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=<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.

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 putall() with default duplication policies.

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

Like a bulk forceput().

putall(items, on_dup_key=<DUP_POLICY.RAISE>, on_dup_val=<DUP_POLICY.RAISE>, on_dup_kv=None)[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__() → list

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 is the same as that of regular dictionaries. Items passed in are added in the order they are passed, respecting the current duplication policies in the process.

See also on_dup_key, on_dup_val, on_dup_kv

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

__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__() → int

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_key = <DUP_POLICY.OVERWRITE>
on_dup_kv = None
on_dup_val = <DUP_POLICY.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.

Note that 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_mixins._DelegateKeysAndItemsToFwdm, bidict._mut.MutableBidict

Base class for mutable bidirectional mappings.

__slots__ = ()
__hash__ = None
__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__() → list

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 is the same as that of regular dictionaries. Items passed in are added in the order they are passed, respecting the current duplication policies in the process.

See also on_dup_key, on_dup_val, on_dup_kv

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

__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 policy 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__() → int

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_key = <DUP_POLICY.OVERWRITE>
on_dup_kv = None
on_dup_val = <DUP_POLICY.RAISE>
pop(key, default=<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.

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_key=<DUP_POLICY.RAISE>, on_dup_val=<DUP_POLICY.RAISE>, on_dup_kv=None)

Associate key with val with the specified duplication policies.

If on_dup_kv is None, the on_dup_val policy will be used for it.

For example, if all given duplication policies are 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_key=<DUP_POLICY.RAISE>, on_dup_val=<DUP_POLICY.RAISE>, on_dup_kv=None)

Like a bulk put().

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

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

Like putall() with default duplication policies.

values()

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

Note that 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.DuplicationPolicy[source]

Bases: bidict._marker._Marker

Base class for bidict’s duplication policies.

See also Values Must Be Unique

__slots__ = ()
__add__()

Return self+value.

__class__

alias of builtins.type

__contains__()

Return key in self.

__delattr__()

Implement delattr(self, name).

__dir__() → list

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.

static __new__(_cls, name)

Create new instance of _Marker(name,)

__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__() → int

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(value) → integer -- return number of occurrences of value
index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

property name

Alias for field number 0

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__() → list

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__() → int

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 RAISE duplication policy.

__cause__

exception cause

__class__

alias of builtins.type

__context__

exception context

__delattr__()

Implement delattr(self, name).

__dir__() → list

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__() → int

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__() → list

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__() → int

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__() → list

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__() → int

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__() → list

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__() → int

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__

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

Bases: bidict._delegating_mixins._DelegateKeysAndItemsToFwdm, 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__() → list

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 is the same as that of regular dictionaries. Items passed in are added in the order they are passed, respecting the current duplication policies in the process.

See also on_dup_key, on_dup_val, on_dup_kv

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

__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__() → int

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_key = <DUP_POLICY.OVERWRITE>
on_dup_kv = None
on_dup_val = <DUP_POLICY.RAISE>
values()

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

Note that 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.FrozenOrderedBidict(*args, **kw)

Bases: bidict._delegating_mixins._DelegateKeysToFwdm, bidict._orderedbase.OrderedBidictBase

Hashable, immutable, ordered bidict type.

__class__

alias of abc.ABCMeta

__contains__(key)
__copy__()

Used for the copy protocol.

See also the copy module

__delattr__()

Implement delattr(self, name).

__dir__() → list

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

The hash of this bidict as determined by its items.

__init__(*args, **kw)

Make a new ordered bidirectional mapping. The signature is the same as that of regular dictionaries. Items passed in are added in the order they are passed, respecting this bidict type’s duplication policies along the way. 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)

An iterator over this bidict’s items in 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__()

An iterator over this bidict’s items in reverse order.

__setattr__()

Implement setattr(self, name, value).

__setstate__(state)

Implemented because use of __slots__ would prevent unpickling otherwise.

See also object.__setstate__()

__sizeof__() → int

size of object in memory, in bytes

__slots__ = ()
__str__()

Return str(self).

classmethod __subclasshook__(C)

Abstract classes can override this to customize issubclass().

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

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

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

on_dup_key = <DUP_POLICY.OVERWRITE>
on_dup_kv = None
on_dup_val = <DUP_POLICY.RAISE>
values()

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

Note that 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.

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 is the same as that of regular dictionaries. Items passed in are added in the order they are passed, respecting this bidict type’s duplication policies along the way. 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]

An iterator over this bidict’s items in order.

__reversed__()[source]

An iterator over this bidict’s items in reverse 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__() → list

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__() → int

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_key = <DUP_POLICY.OVERWRITE>
on_dup_kv = None
on_dup_val = <DUP_POLICY.RAISE>
values()

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

Note that 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__ = ()
__hash__ = None
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__() → list

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 is the same as that of regular dictionaries. Items passed in are added in the order they are passed, respecting this bidict type’s duplication policies along the way. 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)

An iterator over this bidict’s items in 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__()

An iterator over this bidict’s items in reverse 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 policy 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__() → int

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_key = <DUP_POLICY.OVERWRITE>
on_dup_kv = None
on_dup_val = <DUP_POLICY.RAISE>
pop(key, default=<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.

put(key, val, on_dup_key=<DUP_POLICY.RAISE>, on_dup_val=<DUP_POLICY.RAISE>, on_dup_kv=None)

Associate key with val with the specified duplication policies.

If on_dup_kv is None, the on_dup_val policy will be used for it.

For example, if all given duplication policies are 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_key=<DUP_POLICY.RAISE>, on_dup_val=<DUP_POLICY.RAISE>, on_dup_kv=None)

Like a bulk put().

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

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

Like putall() with default duplication policies.

values()

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

Note that 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.

bidict.RAISE = <DUP_POLICY.RAISE>

Base class for bidict’s duplication policies.

See also Values Must Be Unique

bidict.OVERWRITE = <DUP_POLICY.OVERWRITE>

Base class for bidict’s duplication policies.

See also Values Must Be Unique

bidict.IGNORE = <DUP_POLICY.IGNORE>

Base class for bidict’s duplication policies.

See also Values Must Be Unique

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 = 6
bidict.compat.PY2 = False
bidict.compat.PYIMPL = 'CPython'
bidict.compat.CPY = True
bidict.compat.PYPY = False
bidict.compat.DICTS_ORDERED = True
bidict.compat.viewkeys = operator.methodcaller('keys')
bidict.compat.viewvalues = operator.methodcaller('values')
bidict.compat.viewitems = operator.methodcaller('items')
bidict.compat.iterkeys(x)
bidict.compat.itervalues(x)
bidict.compat.iteritems(x)
bidict.compat.abstractproperty(x)
bidict.compat.izip

alias of builtins.zip