Question

The documentation for the Queue.PriorityQueue class in Python is shown here:

https://docs.python.org/2/library/queue.html#Queue.PriorityQueue

It says, "A typical pattern for entries is a tuple in the form: (priority_number, data)"

However, when I try to input basic data into a Priority Queue, I get:

from Queue import PriorityQueue
pq = PriorityQueue()
pq.put(1, "one")
pq.put(2, "two")
pq.put(3, "three")
pq.get()
1
pq.get()
2
pq.get()
3

Isn't the first value in pq.put() the priority, and the second value is the data? It seems like this is reversed. Then when I try to input (data, priority), I get:

from Queue import PriorityQueue
pq = PriorityQueue()
pq.put("two", 4)
pq.put("one", 2)
pq.put("three", 6)
pq.get()
'one'
pq.get()
'three'
pq.get()
'two'

This not in correct order, because it should output, "one, two, three" Any thoughts?

Was it helpful?

Solution

The first value is the priority. The lowest priority comes out of the queue first, so you first example makes sense. The second example is correct also, because in alphabetical order "one" < "three" < "two". It's treating your strings as the priorities and sorting by them. As it says at the page you linked:

"The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0])."

Also you may want to be putting tuples into the queue, I'm not sure, e.g.

pq.put((1, "some data"))
pq.put((2, "some lower priority data"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top