Debian Codegraph @

docs/intro.rst

raw
1 Introduction
2 ============
3
4 The :mod:`bidict` library provides
5 several friendly, efficient data structures
6 for working with
7 `bidirectional mappings <https://en.wikipedia.org/wiki/Bidirectional_map>`__
8 in Python.
9
10 bidict.bidict
11 -------------
12
13 :class:`bidict.bidict`
14 is the main bidirectional mapping data structure provided.
15 It allows looking up the value associated with a key,
16 just like a :class:`dict`:
17
18 .. doctest::
19
20 >>> element_by_symbol = bidict({'H': 'hydrogen'})
21 >>> element_by_symbol['H']
22 'hydrogen'
23
24 But it also allows looking up the key associated with a value,
25 via the special :attr:`~bidict.BidictBase.inverse` attribute:
26
27 .. doctest::
28
29 >>> element_by_symbol.inverse['hydrogen']
30 'H'
31
32 The :attr:`~bidict.BidictBase.inverse` attribute actually
33 references the entire inverse bidirectional mapping:
34
35 .. doctest::
36
37 >>> element_by_symbol
38 bidict({'H': 'hydrogen'})
39 >>> element_by_symbol.inverse
40 bidict({'hydrogen': 'H'})
41
42 ...which is automatically kept in sync
43 as the original mapping is updated:
44
45 .. doctest::
46
47 >>> element_by_symbol['H'] = 'hydrogène'
48 >>> element_by_symbol.inverse
49 bidict({'hydrogène': 'H'})
50
51 If you're used to working with :class:`dict`\s,
52 you'll feel right at home using :mod:`bidict`:
53
54 >>> dir(element_by_symbol)
55 [..., '__getitem__', ..., '__setitem__', ..., 'items', 'keys', ...]
56
57 Familiar, concise, Pythonic.
58
59
60 Why can't I just use a dict?
61 ----------------------------
62
63 A skeptic writes:
64
65 If I want a mapping associating *a* → *b* and *b* → *a*,
66 I can just create the dict ``{a: b, b: a}``.
67 Why bother using :mod:`bidict`?
68
69 One answer is better ergonomics
70 for maintaining a correct representation.
71 For example, to get the correct length,
72 you'd have to take the number reported by :func:`len`
73 and cut it in half.
74
75 But now consider what happens when we need
76 to store a new association,
77 and we try to do so naively:
78
79 .. code-block:: python
80
81 el_by_sym = {'H': 'hydrogen', 'hydrogen': 'H'}
82 # Later we need to associate 'H' with a different value
83 el_by_sym.update({'H': 'hydrogène', 'hydrogène': 'H'} # Too naive
84
85 Here is what we're left with:
86
87 .. code-block:: python
88
89 # el_by_sym:
90 {'H': 'hydrogène', 'hydrogène': 'H', 'hydrogen': 'H'}
91
92 Oops.
93
94 We forgot to look up whether
95 the key and value we wanted to set
96 already had any previous associations
97 and remove them as necessary.
98
99 In general, if we want to store the association *k* ⟷ *v*,
100 but we may have already stored the associations *k* ⟷ *v′* or *k′* ⟷ *v*,
101 a correct implementation using the single-dict approach
102 would require code like this:
103
104 .. doctest::
105
106 >>> d = {'H': 'hydrogen', 'hydrogen': 'H'}
107
108 >>> def update(d, key, val):
109 ... oldval = d.pop(key, object())
110 ... d.pop(oldval, None)
111 ... oldkey = d.pop(val, object())
112 ... d.pop(oldkey, None)
113 ... d.update({key: val, val: key})
114
115 >>> update(d, 'H', 'hydrogène')
116 >>> d == {'H': 'hydrogène', 'hydrogène': 'H'}
117 True
118
119
120 With :mod:`bidict`, we can instead just write:
121
122 .. doctest::
123
124 >>> b = bidict({'H': 'hydrogen'})
125 >>> b['H'] = 'hydrogène'
126
127 And :mod:`bidict` takes care of all the fussy details,
128 leaving us with just what we wanted:
129
130 .. doctest::
131
132 >>> b
133 bidict({'H': 'hydrogène'})
134
135 >>> b.inverse
136 bidict({'hydrogène': 'H'})
137
138
139 Even more important...
140 ++++++++++++++++++++++
141
142 Beyond this,
143 consider what would happen if we needed to work with
144 just the keys, values, or items that we have associated.
145
146 Since the single-dict approach
147 inserts values as keys into the same dict that it inserts keys into,
148 we'd never be able to tell our keys and values apart.
149
150 So iterating over the keys would also yield the values
151 (and vice versa),
152 with no way to tell which was which.
153
154 Iterating over the items
155 would yield twice as many as we wanted,
156 with a *(v, k)* item that we'd have to ignore
157 for each *(k, v)* item that we expect,
158 and no way to tell which was which.
159
160 .. doctest::
161
162 >>> # Compare the single-dict approach:
163 >>> set(d.keys()) == {'H', 'hydrogène'} # .keys() also gives values
164 True
165 >>> set(d.values()) == {'H', 'hydrogène'} # .values() also gives keys
166 True
167
168 >>> # ...to using a bidict:
169 >>> b.keys() == {'H'} # just the keys
170 True
171 >>> b.values() == {'hydrogène'} # just the values
172 True
173
174 In short,
175 to model a bidirectional mapping correctly and unambiguously,
176 we need two separate one-directional mappings,
177 one for the forward associations and one for the inverse,
178 that are kept in sync as the associations change.
179
180 This is exactly what :mod:`bidict` does under the hood,
181 abstracting it into a clean and ergonomic interface.
182
183 :mod:`bidict`'s APIs also provide power, flexibility, and safety,
184 making sure the one-to-one invariant is maintained
185 and inverse mappings are kept consistent,
186 while also helping make sure you don't accidentally
187 :ref:`shoot yourself in the foot <basic-usage:Values Must Be Unique>`.
188
189
190 Additional Functionality
191 ------------------------
192
193 Besides the standard :class:`bidict.bidict` type,
194 the :mod:`bidict` module provides other bidirectional mapping variants:
195 :class:`~bidict.frozenbidict` and
196 :class:`~bidict.OrderedBidict`.
197
198 These and :mod:`bidict`'s other functionality
199 will be covered in later sections.
200
201 But first, let's look at a few more details of :doc:`basic-usage`.