Python Recipes Flashcards
(11 cards)
Implementing priority queue class (push and pop methods)
Push:
heapq. heappush(self._queue, (-priority, self._index, item))
self. _index += 1
Pop:
return heapq.heappop(self._queue)[-1]
Mapping keys to multiple values
Use defaultdict from collections
Finding min, max and sorting of dictionary
min_price = min( zip( prices.values(), prices.keys() ) ) #min_price is (10.75, 'FB')
prices_sorted = sorted( zip( ... ) ) # prices_sorted is [ (10.75, 'FB'), ... ]
Finding commonalities in dictionaries
Keys views support common set operations.
a. keys() & b.keys()
a. keys() - b.keys()
Removing duplicates from a sequence while maintaining order
If items are hashable, then
def dedupe (items): seen = set() for item in items: if item not in seen: yield item seen.add( item)
Determining most frequently occurring items in a sequence
Use Counter in collections
word_counter = Counter( words) top_three = word_counter.most_common(3)
word_counter.update( more_words)
Counters can be added and subtracted as well
Sorting list of dictionaries by a common key
Use itemgetter:
rows_by_uid = sorted(rows, key=itemgetter(‘uid’))
You can also use lambda expression:
rows_by_uid = sorted(rows, key=lambda r: r[‘uid’])
Sorting objects without native comparison support
Attrgetter:
sorted( users, key=attrgetter(‘user_id’)
Can also use lambda expression
Group by
from itertools import groupby
rows.sort(key=itemgetter(‘date’))
for date, items in groupby(rows, key=itemgetter(‘date’)):
…
!!!Groupby won’t work without sorting it first!!!
Filtering sequence elements
List comprehension, Generator expressions
If filtering process is more complicated, then use filter:
def is_int(val): try: x = int(val) return True except ValueError: return False
ivals = list( filter( is_int, values))
Transforming and reducing data
Use generator expression arguments:
s = sum(x*x for x in nums)