Priority Queue using Queue and Heapdict module in Python (original) (raw)

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:

**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:

**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()))

`