Table of Contents

Python3 Priority Queues

Insertion & Removal

pq.py
import queue
 
q = queue.PriorityQueue()
q.put(10)
q.put(1)
q.put(5)
while not q.empty():
    print(q.get())    # 1 5 10

Modifying Priority

Unlike C++ and Java, the standard priority queue in Python3 does not take a comparator on declaration. There are two means of dealing with a modified priority or a priority that is separate from the object:

In many instances the former is fastest.

E.g., If we wish to sort individuals by zip code, street name, address, and name, we would create the tuple:
(zip, street, address, name) for insertion.

pq_tuple.py
import queue
 
q = queue.PriorityQueue()
 
q.put((65412, "ABC Rd.", 204, "Berry"))
q.put((65412, "Z3 Dr.", 459, "Zuse"))
q.put((65412, "ABC Rd.", 123, "Atanasoff"))
q.put((65400, "Analytical Ct.", 000, "Babbage"))
 
while not q.empty():
    print(q.get())   # Babbage, Atanasoff, Berry, Zuse