Priority Queue using Queue and Heapdict module in Python

Last Updated : 8 Jan, 2026

A Priority Queue is a special type of queue where elements with higher priority are dequeued before elements with lower priority. If two elements have the same priority, they are served according to their order in the queue.

Let's learn how to use Priority Queue in Python with queue.PriorityQueue and heapdict.

Using queue.PriorityQueue

queue.PriorityQueue is a constructor to create a priority queue, where items are stored in priority order (lower priority numbers are retrieved first).

Functions:

  • put(): Puts an item into the queue.
  • get(): Removes and returns an item from the queue.
  • qsize(): Returns the current queue size.
  • empty(): Returns True if the queue is empty, False otherwise. It is equivalent to qsize()==0.
  • full(): Returns True if the queue is full, False otherwise. It is equivalent to qsize()>=maxsize.

Note : empty(), full(), qsize() are not reliable as they risk race condition where the queue size might change.

Example:

Python
from queue import PriorityQueue

pq = PriorityQueue()

pq.put((2, 'g'))
pq.put((3, 'e'))
pq.put((4, 'k'))
pq.put((5, 's'))
pq.put((1, 'e'))

print(pq.get())
print(pq.get())  

print('Items in queue:', pq.qsize())
print('Is queue empty:', pq.empty())
print('Is queue full:', pq.full())

Output
(1, 'e')
(2, 'g')
Items in queue: 3
Is queue empty: False
Is queue full: False

Using heapdict()

Heapdict is a dictionary-based priority queue that allows accessing and removing the lowest-priority item and efficiently updating priorities, useful in algorithms like Dijkstra’s and A*.

Functions:

  • clear(): Removes all items.
  • peekitem(): Returns (key, value) with lowest value; raises KeyError if empty.
  • popitem(): Removes and returns (key, value) with lowest value; raises KeyError if empty.
  • get(key, default=None): Returns value for key if exists, else default.
  • items(): Returns a view of (key, value) pairs.
  • keys(): Returns a view of all keys.
  • values(): Returns a view of all values.

Example:

Python
import heapdict

h = heapdict.heapdict()
h['g'] = 2
h['e'] = 1
h['k'] = 3
h['s'] = 4

print('All items:', list(h.items()))
print('Lowest priority pair:', h.peekitem())
print('Remove lowest priority:', h.popitem())
print('Get value for key 5:', h.get(5, 'Not found'))

h.clear()
print('All items after clear:', list(h.items()))

Output

All items: [('g', 2), ('e', 1), ('k', 3), ('s', 4)]
Lowest priority pair: ('e', 1)
Remove lowest priority: ('e', 1)
Get value for key 5: Not found
All items after clear: []

Comment

Explore