Search code examples
python-3.xqueuepriority-queue

Python PriorityQueue. How to get() the data element instead of its priority number?


I was wondering if there is any way to retrieve just the data element itself from a PriorityQueue instead of its priority number.

The example below prints number "11", as expected. However, I need it to print the string "item A" only.

When I try:

a = q.get()[1]

I just get a TypeError saying "'int' object is not subscriptable".

Could anyone please point me in the right direction?

from queue import PriorityQueue

q = PriorityQueue()

q.put(11, "item A")

a = q.get()

print(a)

Output:

11

Solution

  • try this.

    from queue import PriorityQueue
    q = PriorityQueue()
    b  = (11, "item A")
    q.put(b)
    a = q.get()
    print(a[1])