Can I get an item from a PriorityQueue without removing it yet? Can I get an item from a PriorityQueue without removing it yet? python python

Can I get an item from a PriorityQueue without removing it yet?


If a is a PriorityQueue object, You can use a.queue[0] to get the next item:

from queue import PriorityQueuea = PriorityQueue()a.put((10, "a"))a.put((4, "b"))a.put((3,"c"))print(a.queue[0])print(a.queue)print(a.get())print(a.queue)print(a.get())print(a.queue)

output is :

(3, 'c')[(3, 'c'), (10, 'a'), (4, 'b')](3, 'c')[(4, 'b'), (10, 'a')](4, 'b')[(10, 'a')]

but be careful about multi thread access.


If you want next element in the PriorityQueue, in the order of the insertion of the elements, use:

for i in range(len(queue.queue)):    print queue.queue[i]

this will not pop anything out.

If you want it in the priority order, use:

for i in range(len(queue.queue)):    temp = queue.get()    queue.put(temp)    print temp

If you are using a tuple, instead of a single variable, replace temp by:

((temp1,temp2))


Assuming your items stored in the PriorityQueue is a tuple (priority, value),

def peek(pq):  return pq.queue[0][1]