Priority queue with higher priority first in Python

Ashok picture Ashok · Feb 27, 2013 · Viewed 11.4k times · Source

I need a priority queue that gets the item with the highest priority value first. I'm currently using the PriorityQueue Class from the Queue library. However, this function only returns the items with the lowest value first. I tried some ugly solutions like (sys.maxint - priority) as the priority, but was just wondering if a more elegant solution exists.

Answer

Martijn Pieters picture Martijn Pieters · Feb 27, 2013

Use a negative priority instead, no need to subtract from sys.maxint.

queue.put((-priority, item))

An item with priority -10 will be returned before items with priority -5, for example.