Search code examples
pythonpriority-queue

Python PriorityQueue order


I'm trying to figure out in what order PriorityQueue.get() returns values in Python. First I thought that the smaller priority values get returned first but after few examples it's not like that. This is the example that I have run:

>>> qe = PriorityQueue()
>>> qe.put("Br", 0)
>>> qe.put("Sh", 0.54743812441605)
>>> qe.put("Gl", 1.1008112004388)

>>> qe.get()
'Br'
>>> qe.get()
'Gl'
>>> qe.get()
'Sh'

Why is it returning values in this order?


Solution

  • According to doc, the first parameter is priority, and second - is value. So that's why you get such result.

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

    So you should pass a tuple to put like this:

    >>> q = PriorityQueue()
    >>> q.put((10,'ten'))
    >>> q.put((1,'one'))
    >>> q.put((5,'five'))
    >>> q.get()
    >>> (1, 'one')
    >>> q.get()
    >>> (5, 'five')
    >>> q.get()
    >>> (10, 'ten')
    

    Notice additional braces.