After writing about Default Dictionary in Python some time ago, now it is time to take a look at the ordered dictionary and the heap queue as these are built-in structures, coming out of the box. And they are fancy.
Ordered Dictionary
A normal dictionary in python implements a hash table. And hash tables are not ordered. In any language. Well, the good thing here is that we have ordered dictionary thus, we may count on the order of the elements. The first one coming will be the first one displayed, if we loop through it:
1 2 3 4 5 6 7 8 9 |
from collections import OrderedDict my_dict = OrderedDict() my_dict['Vitosh'] = 'Academy' my_dict['dot'] = 'com' my_dict['foo'] = 'bar' for key, value in my_dict.items(): print(f"{key} -> {value}") |
Heap Queue
Heap queue provides implementation of the priority queue algorithm. With other words, we got no first-in-first-out here, but we follow the priority. In our case below, the priority is given by the first numeric element of the tuple:
1 2 3 4 5 6 7 8 9 10 11 12 |
import heapq from heapq import heappush my_heap = [] heappush(my_heap, (2, "wake up")) heappush(my_heap, (1, "stop sleeping")) heappush(my_heap, (10, "put a little makeup")) heappush(my_heap, (9, "you wanted to")) print(my_heap) for _ in range(len(my_heap)): print(heapq.heappop(my_heap)) |
And the result is quite expected:
1 2 3 4 5 |
[(1, 'stop sleeping'), (2, 'wake up'), (10, 'put a little makeup'), (9, 'you wanted to')] (1, 'stop sleeping') (2, 'wake up') (9, 'you wanted to') (10, 'put a little makeup') |
Turning a simple list into a heap is done with heapify() :
1 2 3 4 5 6 7 8 |
my_heap2 = [5,6,4,3,4] heapq.heapify(my_heap2) print(my_heap2) for _ in range(1,4): heapq.heappop(my_heap2) print(my_heap2) |
So, heapify() , heappush() and heappop() are the 3 most important functions to use with heapq. For the others, the python documentation is quite well written – https://docs.python.org/3/library/heapq.html
🙂