Debian Codegraph @

petl/util/lookups.py

raw
1 from __future__ import absolute_import, print_function, division
2
3
4 import operator
5 from petl.compat import text_type
6
7
8 from petl.errors import DuplicateKeyError
9 from petl.util.base import Table, asindices, asdict, Record, rowgetter
10
11
12 def _setup_lookup(table, key, value):
13
14 # obtain iterator and header row
15 it = iter(table)
16 try:
17 hdr = next(it)
18 except StopIteration:
19 hdr = []
20
21 # prepare key getter
22 keyindices = asindices(hdr, key)
23 assert len(keyindices) > 0, 'no key selected'
24 getkey = operator.itemgetter(*keyindices)
25
26 # prepare value getter
27 if value is None:
28 # default value is complete row
29 getvalue = rowgetter(*range(len(hdr)))
30 else:
31 valueindices = asindices(hdr, value)
32 assert len(valueindices) > 0, 'no value selected'
33 getvalue = operator.itemgetter(*valueindices)
34
35 return it, getkey, getvalue
36
37
38 def lookup(table, key, value=None, dictionary=None):
39 """
40 Load a dictionary with data from the given table. E.g.::
41
42 >>> import petl as etl
43 >>> table1 = [['foo', 'bar'],
44 ... ['a', 1],
45 ... ['b', 2],
46 ... ['b', 3]]
47 >>> lkp = etl.lookup(table1, 'foo', 'bar')
48 >>> lkp['a']
49 [1]
50 >>> lkp['b']
51 [2, 3]
52 >>> # if no value argument is given, defaults to the whole
53 ... # row (as a tuple)
54 ... lkp = etl.lookup(table1, 'foo')
55 >>> lkp['a']
56 [('a', 1)]
57 >>> lkp['b']
58 [('b', 2), ('b', 3)]
59 >>> # compound keys are supported
60 ... table2 = [['foo', 'bar', 'baz'],
61 ... ['a', 1, True],
62 ... ['b', 2, False],
63 ... ['b', 3, True],
64 ... ['b', 3, False]]
65 >>> lkp = etl.lookup(table2, ('foo', 'bar'), 'baz')
66 >>> lkp[('a', 1)]
67 [True]
68 >>> lkp[('b', 2)]
69 [False]
70 >>> lkp[('b', 3)]
71 [True, False]
72 >>> # data can be loaded into an existing dictionary-like
73 ... # object, including persistent dictionaries created via the
74 ... # shelve module
75 ... import shelve
76 >>> lkp = shelve.open('example1.dat', flag='n')
77 >>> lkp = etl.lookup(table1, 'foo', 'bar', lkp)
78 >>> lkp.close()
79 >>> lkp = shelve.open('example1.dat', flag='r')
80 >>> lkp['a']
81 [1]
82 >>> lkp['b']
83 [2, 3]
84
85 """
86
87 if dictionary is None:
88 dictionary = dict()
89
90 # setup
91 it, getkey, getvalue = _setup_lookup(table, key, value)
92
93 # build lookup dictionary
94 for row in it:
95 k = getkey(row)
96 v = getvalue(row)
97 if k in dictionary:
98 # work properly with shelve
99 l = dictionary[k]
100 l.append(v)
101 dictionary[k] = l
102 else:
103 dictionary[k] = [v]
104
105 return dictionary
106
107
108 Table.lookup = lookup
109
110
111 def lookupone(table, key, value=None, dictionary=None, strict=False):
112 """
113 Load a dictionary with data from the given table, assuming there is
114 at most one value for each key. E.g.::
115
116 >>> import petl as etl
117 >>> table1 = [['foo', 'bar'],
118 ... ['a', 1],
119 ... ['b', 2],
120 ... ['b', 3]]
121 >>> # if the specified key is not unique and strict=False (default),
122 ... # the first value wins
123 ... lkp = etl.lookupone(table1, 'foo', 'bar')
124 >>> lkp['a']
125 1
126 >>> lkp['b']
127 2
128 >>> # if the specified key is not unique and strict=True, will raise
129 ... # DuplicateKeyError
130 ... try:
131 ... lkp = etl.lookupone(table1, 'foo', strict=True)
132 ... except etl.errors.DuplicateKeyError as e:
133 ... print(e)
134 ...
135 duplicate key: 'b'
136 >>> # compound keys are supported
137 ... table2 = [['foo', 'bar', 'baz'],
138 ... ['a', 1, True],
139 ... ['b', 2, False],
140 ... ['b', 3, True],
141 ... ['b', 3, False]]
142 >>> lkp = etl.lookupone(table2, ('foo', 'bar'), 'baz')
143 >>> lkp[('a', 1)]
144 True
145 >>> lkp[('b', 2)]
146 False
147 >>> lkp[('b', 3)]
148 True
149 >>> # data can be loaded into an existing dictionary-like
150 ... # object, including persistent dictionaries created via the
151 ... # shelve module
152 ... import shelve
153 >>> lkp = shelve.open('example2.dat', flag='n')
154 >>> lkp = etl.lookupone(table1, 'foo', 'bar', lkp)
155 >>> lkp.close()
156 >>> lkp = shelve.open('example2.dat', flag='r')
157 >>> lkp['a']
158 1
159 >>> lkp['b']
160 2
161
162 """
163
164 if dictionary is None:
165 dictionary = dict()
166
167 # setup
168 it, getkey, getvalue = _setup_lookup(table, key, value)
169
170 # build lookup dictionary
171 for row in it:
172 k = getkey(row)
173 if strict and k in dictionary:
174 raise DuplicateKeyError(k)
175 elif k not in dictionary:
176 v = getvalue(row)
177 dictionary[k] = v
178
179 return dictionary
180
181
182 Table.lookupone = lookupone
183
184
185 def dictlookup(table, key, dictionary=None):
186 """
187 Load a dictionary with data from the given table, mapping to dicts. E.g.::
188
189 >>> import petl as etl
190 >>> table1 = [['foo', 'bar'],
191 ... ['a', 1],
192 ... ['b', 2],
193 ... ['b', 3]]
194 >>> lkp = etl.dictlookup(table1, 'foo')
195 >>> lkp['a']
196 [{'foo': 'a', 'bar': 1}]
197 >>> lkp['b']
198 [{'foo': 'b', 'bar': 2}, {'foo': 'b', 'bar': 3}]
199 >>> # compound keys are supported
200 ... table2 = [['foo', 'bar', 'baz'],
201 ... ['a', 1, True],
202 ... ['b', 2, False],
203 ... ['b', 3, True],
204 ... ['b', 3, False]]
205 >>> lkp = etl.dictlookup(table2, ('foo', 'bar'))
206 >>> lkp[('a', 1)]
207 [{'foo': 'a', 'bar': 1, 'baz': True}]
208 >>> lkp[('b', 2)]
209 [{'foo': 'b', 'bar': 2, 'baz': False}]
210 >>> lkp[('b', 3)]
211 [{'foo': 'b', 'bar': 3, 'baz': True}, {'foo': 'b', 'bar': 3, 'baz': False}]
212 >>> # data can be loaded into an existing dictionary-like
213 ... # object, including persistent dictionaries created via the
214 ... # shelve module
215 ... import shelve
216 >>> lok = shelve.open('example3.dat', flag='n')
217 >>> lok = etl.dictlookup(table1, 'foo', lok)
218 >>> lok.close()
219 >>> lup = shelve.open('example3.dat', flag='r')
220 >>> lup['a']
221 [{'foo': 'a', 'bar': 1}]
222 >>> lup['b']
223 [{'foo': 'b', 'bar': 2}, {'foo': 'b', 'bar': 3}]
224
225 """
226
227 if dictionary is None:
228 dictionary = dict()
229
230 it = iter(table)
231 try:
232 hdr = next(it)
233 except StopIteration:
234 hdr = []
235 flds = list(map(text_type, hdr))
236 keyindices = asindices(hdr, key)
237 assert len(keyindices) > 0, 'no key selected'
238 getkey = operator.itemgetter(*keyindices)
239 for row in it:
240 k = getkey(row)
241 rec = asdict(flds, row)
242 if k in dictionary:
243 # work properly with shelve
244 l = dictionary[k]
245 l.append(rec)
246 dictionary[k] = l
247 else:
248 dictionary[k] = [rec]
249 return dictionary
250
251
252 Table.dictlookup = dictlookup
253
254
255 def dictlookupone(table, key, dictionary=None, strict=False):
256 """
257 Load a dictionary with data from the given table, mapping to dicts,
258 assuming there is at most one row for each key. E.g.::
259
260 >>> import petl as etl
261 >>> table1 = [['foo', 'bar'],
262 ... ['a', 1],
263 ... ['b', 2],
264 ... ['b', 3]]
265 >>> # if the specified key is not unique and strict=False (default),
266 ... # the first value wins
267 ... lkp = etl.dictlookupone(table1, 'foo')
268 >>> lkp['a']
269 {'foo': 'a', 'bar': 1}
270 >>> lkp['b']
271 {'foo': 'b', 'bar': 2}
272 >>> # if the specified key is not unique and strict=True, will raise
273 ... # DuplicateKeyError
274 ... try:
275 ... lkp = etl.dictlookupone(table1, 'foo', strict=True)
276 ... except etl.errors.DuplicateKeyError as e:
277 ... print(e)
278 ...
279 duplicate key: 'b'
280 >>> # compound keys are supported
281 ... table2 = [['foo', 'bar', 'baz'],
282 ... ['a', 1, True],
283 ... ['b', 2, False],
284 ... ['b', 3, True],
285 ... ['b', 3, False]]
286 >>> lkp = etl.dictlookupone(table2, ('foo', 'bar'))
287 >>> lkp[('a', 1)]
288 {'foo': 'a', 'bar': 1, 'baz': True}
289 >>> lkp[('b', 2)]
290 {'foo': 'b', 'bar': 2, 'baz': False}
291 >>> lkp[('b', 3)]
292 {'foo': 'b', 'bar': 3, 'baz': True}
293 >>> # data can be loaded into an existing dictionary-like
294 ... # object, including persistent dictionaries created via the
295 ... # shelve module
296 ... import shelve
297 >>> lkp = shelve.open('example4.dat', flag='n')
298 >>> lkp = etl.dictlookupone(table1, 'foo', lkp)
299 >>> lkp.close()
300 >>> lkp = shelve.open('example4.dat', flag='r')
301 >>> lkp['a']
302 {'foo': 'a', 'bar': 1}
303 >>> lkp['b']
304 {'foo': 'b', 'bar': 2}
305
306 """
307
308 if dictionary is None:
309 dictionary = dict()
310
311 it = iter(table)
312 try:
313 hdr = next(it)
314 except StopIteration:
315 hdr = []
316 flds = list(map(text_type, hdr))
317 keyindices = asindices(hdr, key)
318 assert len(keyindices) > 0, 'no key selected'
319 getkey = operator.itemgetter(*keyindices)
320 for row in it:
321 k = getkey(row)
322 if strict and k in dictionary:
323 raise DuplicateKeyError(k)
324 elif k not in dictionary:
325 d = asdict(flds, row)
326 dictionary[k] = d
327 return dictionary
328
329
330 Table.dictlookupone = dictlookupone
331
332
333 def recordlookup(table, key, dictionary=None):
334 """
335 Load a dictionary with data from the given table, mapping to record objects.
336
337 """
338
339 if dictionary is None:
340 dictionary = dict()
341
342 it = iter(table)
343 try:
344 hdr = next(it)
345 except StopIteration:
346 hdr = []
347 flds = list(map(text_type, hdr))
348 keyindices = asindices(hdr, key)
349 assert len(keyindices) > 0, 'no key selected'
350 getkey = operator.itemgetter(*keyindices)
351 for row in it:
352 k = getkey(row)
353 rec = Record(row, flds)
354 if k in dictionary:
355 # work properly with shelve
356 l = dictionary[k]
357 l.append(rec)
358 dictionary[k] = l
359 else:
360 dictionary[k] = [rec]
361 return dictionary
362
363
364 Table.recordlookup = recordlookup
365
366
367 def recordlookupone(table, key, dictionary=None, strict=False):
368 """
369 Load a dictionary with data from the given table, mapping to record objects,
370 assuming there is at most one row for each key.
371
372 """
373
374 if dictionary is None:
375 dictionary = dict()
376
377 it = iter(table)
378 try:
379 hdr = next(it)
380 except StopIteration:
381 hdr = []
382 flds = list(map(text_type, hdr))
383 keyindices = asindices(hdr, key)
384 assert len(keyindices) > 0, 'no key selected'
385 getkey = operator.itemgetter(*keyindices)
386 for row in it:
387 k = getkey(row)
388 if strict and k in dictionary:
389 raise DuplicateKeyError(k)
390 elif k not in dictionary:
391 d = Record(row, flds)
392 dictionary[k] = d
393 return dictionary
394
395
396 Table.recordlookupone = recordlookupone