![]() |
VOOZH | about |
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.
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:
(1, 'e') (2, 'g') Items in queue: 3 Is queue empty: False Is queue full: False
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:
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: []