VOOZH about

URL: https://www.geeksforgeeks.org/python/priority-queue-using-queue-and-heapdict-module-in-python/

⇱ Priority Queue using Queue and Heapdict module in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:


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:

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: []

Related Articles:

Comment