Python – Ordered Dictionary and Heap Queue

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 is like a walk in the park.

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:

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:

And the result is quite expected:

Turning a simple list into a heap is done with heapify() :

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

🙂

Tagged with: , , , ,