How to use Priority Queue in Python

The Priority Queue is implemented with binary heap. To understand how it’s implemented, refer to this post. Python provides a built-in implementation of the Priority Queue data structure.

For insertion, it uses the put function. The get function dequeues the highest priority item from the queue.

To use the Priority Queue class object:

1
2
3
from queue import PriorityQueue

q = PriorityQueue()

To insert a tuple pair which has a priority associated with it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
q.put((2, "Joe"))
q.put((1, "Tim"))
q.put((4, "Watson"))

print(q.get())

print(q.empty())
print(q.full())

q.put((3, "Michael"))
print(q.get())

while not q.empty():
print(q.get())

print(q.empty())

Output:

(1,'Tim')
False
False
(2,'Joe')
(3,'Michael')
(4,"watson)
True

To simply insert values as priority:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
q.put(12)
q.put(20)
print(q.qsize())
q.put(15)
print(q.qsize())
while not q.empty():
print(q.get())
print(q.empty())

Output:

2
3
12
15
20
True