mirror of https://github.com/jab/bidict.git
35 lines
937 B
Plaintext
35 lines
937 B
Plaintext
![]() |
Test script for :class:`bidict.inverted`::
|
||
|
|
||
|
>>> from bidict import inverted
|
||
|
>>> keys = (1, 2, 3)
|
||
|
>>> vals = ('one', 'two', 'three')
|
||
|
>>> fwd = dict(zip(keys, vals))
|
||
|
>>> inv = dict(inverted(fwd))
|
||
|
>>> inv == dict(zip(vals, keys))
|
||
|
True
|
||
|
|
||
|
Passing an iterable of pairs produces an iterable of the pairs' inverses::
|
||
|
|
||
|
>>> seq = [(1, 'one'), (2, 'two'), (3, 'three')]
|
||
|
>>> list(inverted(seq))
|
||
|
[('one', 1), ('two', 2), ('three', 3)]
|
||
|
|
||
|
Anything yielding pairs works too::
|
||
|
|
||
|
>>> list(inverted((i*i, i) for i in range(2, 5)))
|
||
|
[(2, 4), (3, 9), (4, 16)]
|
||
|
|
||
|
Passing an ``inverted`` object back into ``inverted`` produces the original
|
||
|
sequence of pairs::
|
||
|
|
||
|
>>> seq == list(inverted(inverted(seq)))
|
||
|
True
|
||
|
|
||
|
Be careful with passing the inverse of a non-injective mapping into ``dict``::
|
||
|
|
||
|
>>> squares = {-2: 4, -1: 1, 0: 0, 1: 1, 2: 4}
|
||
|
>>> len(squares)
|
||
|
5
|
||
|
>>> len(dict(inverted(squares)))
|
||
|
3
|