Open In App

Priority Queue using Queue and Heapdict module in Python

Last Updated : 31 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Priority Queue is an extension of the queue with the following properties.

  • An element with high priority is dequeued before an element with low priority.
  • If two elements have the same priority, they are served according to their order in the queue.

queue.PriorityQueue(maxsize)

It is a constructor for a priority queue. maxsize is the number of elements which can be inserted into queue, its default value is 0. If the maxsize value is less than or equal to 0, then queue size is infinite. Items are retrieved priority order (lowest 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:




from queue import PriorityQueue
  
q = PriorityQueue()
  
# insert into queue
q.put((2, 'g'))
q.put((3, 'e'))
q.put((4, 'k'))
q.put((5, 's'))
q.put((1, 'e'))
  
# remove and return 
# lowest priority item
print(q.get())
print(q.get())
  
# check queue size
print('Items in queue :', q.qsize())
  
# check if queue is empty
print('Is queue empty :', q.empty())
  
# check if queue is full
print('Is queue full :', q.full())


Output :

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

heapdict()

Heapdict implements the MutableMapping ABC, meaning it works pretty much like a regular Python dictionary. It’s designed to be used as a priority queue. Along with functions provided by ordinary dict(), it also has popitem() and peekitem() functions which return the pair with the lowest priority. Unlike heapq module, the HeapDict supports efficiently changing the priority of an existing object (“decrease-key” ). Altering the priority is important for many algorithms such as Dijkstra’s Algorithm and A*.

Functions-

  • clear(self) – D.clear() -> None. Remove all items from D.
  • peekitem(self) – D.peekitem() -> (k, v), return the (key, value) pair with lowest value; but raise KeyError if D is empty.
  • popitem(self) – D.popitem() -> (k, v), remove and return the (key, value) pair with lowest value; but raise KeyError if D is empty.
  • get(self, key, default=None) – D.get(k[, d]) -> D[k] if k in D, else d. d defaults to None.
  • items(self) – D.items() -> a set-like object providing a view on D’s items
  • keys(self) – D.keys() -> a set-like object providing a view on D’s keys
  • values(self) – D.values() -> an object providing a view on D’s values

Example:




import heapdict
  
h = heapdict.heapdict()
  
# Adding pairs into heapdict
h['g']= 2
h['e']= 1
h['k']= 3
h['s']= 4
  
print('list of key:value pairs in h:\n'
      list(h.items()))
print('pair with lowest priority:\n',
      h.peekitem())
print('list of keys in h:\n',
      list(h.keys()))
print('list of values in h:\n',
      list(h.values()))
print('remove pair with lowest priority:\n',
      h.popitem())
print('get value for key 5 in h:\n',
      h.get(5, 'Not found'))
  
# clear heapdict h
h.clear()
print(list(h.items()))


Output :

list of key:value pairs in h:
 [('g', 2), ('e', 1), ('k', 3), ('s', 4)]
pair with lowest priority:
 ('e', 1)
list of keys in h:
 ['g', 'e', 'k', 's']
list of values in h:
 [2, 1, 3, 4]
remove pair with lowest priority:
 ('e', 1)
get value for key 5 in h:
 Not found
[]


Previous Article
Next Article

Similar Reads

What is Priority Queue | Introduction to Priority Queue
A priority queue is a type of queue that arranges elements based on their priority values. Elements with higher priority values are typically retrieved before elements with lower priority values. In a priority queue, each element has a priority value associated with it. When you add an element to the queue, it is inserted in a position based on its
15+ min read
Heap and Priority Queue using heapq module in Python
Heaps are widely used tree-like data structures in which the parent nodes satisfy any one of the criteria given below. The value of the parent node in each level is less than or equal to its children's values - min-heap.The value of the parent node in each level higher than or equal to its children's values - max-heap. The heaps are complete binary
5 min read
Difference between Circular Queue and Priority Queue
Queues are fundamental data structures that are used to store and manage a collection of elements. While both circular queues and priority queues are types of queues, they have distinct characteristics and applications. This article will explore the key differences between circular queues and priority queues. Circular Queue:A Circular Queue is an e
4 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
Can we use Simple Queue instead of Priority queue to implement Dijkstra's Algorithm?
What is Dijkstra's Algorithm? Dijkstra's Algorithm is used for finding the shortest path between any two vertices of a graph. It uses a priority queue for finding the shortest path. For more detail, about Dijkstra's Algorithm, you can refer to this article. Why Dijkstra's Algorithm uses a Priority Queue? We use min heap in Dijkstra's Algorithm beca
2 min read
Turn a Queue into a Priority Queue
What is Queue?Queue is an abstract data type that is open at both ends. One end is always used to insert data (enqueue) which is basically the rear/back/tail end and the other which is the front end is used to remove data (dequeue). Queue follows First-In-First-Out (FIFO) methodology, i.e., "the data item stored first will be accessed first". Decla
9 min read
Why does Queue have front but Priority-queue has top in stl?
Why does the queue have front but the priority queue has top in stl? The main difference between a queue and a priority queue is that a queue follows the FIFO (First-In-First-Out) principle, while a priority queue follows a specific priority order. In other words, the elements in a queue are processed in the order they were added, whereas the eleme
8 min read
Priority Queue using Linked List
Implement Priority Queue using Linked Lists. push(): This function is used to insert a new data into the queue.pop(): This function removes the element with the highest priority from the queue.peek() / top(): This function is used to get the highest priority element in the queue without removing it from the queue. Priority Queues can be implemented
12 min read
Priority Queue using Doubly Linked List
Given Nodes with their priority, implement a priority queue using doubly linked list. Prerequisite : Priority Queue push(): This function is used to insert a new data into the queue.pop(): This function removes the element with the lowest priority value from the queue.peek() / top(): This function is used to get the lowest priority element in the q
11 min read
Huffman Coding using Priority Queue
Prerequisite: Greedy Algorithms | Set 3 (Huffman Coding), priority_queue::push() and priority_queue::pop() in C++ STL Given a char array ch[] and frequency of each character as freq[]. The task is to find Huffman Codes for every character in ch[] using Priority Queue. Example Input: ch[] = { 'a', 'b', 'c', 'd', 'e', 'f' }, freq[] = { 5, 9, 12, 13,
12 min read