0

I am adding data in priority queue in the form of (priority,data) but when I use the function get(), I get back my priority instead of data. Also, if I add in the form of (data,priority), it is sorted by data values.

here is my trial code

from Queue import PriorityQueue
q= PriorityQueue(0)
q.put(4,8)
q.put(3,7)
q.put(2,6)
q.put(1,5)
while not q.empty():
    item = q.get()[1]
    print item,
print

q= PriorityQueue(0)
q.put(4,5)
q.put(3,6)
q.put(2,7)
q.put(1,8)
while not q.empty():
    item = q.get()[1]
    print item,
print

first one is giving error TypeError: 'int' object is not iterable and second one TypeError: 'int' object has no attribute 'getitem'

1
  • 4
    Please add your code so far Commented Mar 2, 2014 at 3:48

1 Answer 1

5

A priority queue works like a standard queue except that the items are tuples of priority, item, so get() on such a queue will return that kind of tuple - if you want to get the actual item you should use either this which will give you both the item and its priority :

prio, item = queue.get()

Or directly like this if you don't care about the priority at all :

item = queue.get()[1]

See the official Python documentation for more info.

Edit: your comment shows that you put the values in your queue with put(4, 8), so you're only putting 4 and the 8 becomes the block argument of put() - you need to put a tuple like so :

queue.put((4, 8))
Sign up to request clarification or add additional context in comments.

3 Comments

first one is giving error TypeError: 'int' object is not iterable and second one TypeError: 'int' object has no attribute 'getitem' here is my trial code from Queue import PriorityQueue q= PriorityQueue(0) q.put(4,8) q.put(3,7) q.put(2,6) q.put(1,5) while not q.empty(): item = q.get()[1] print item, print q= PriorityQueue(0) q.put(4,5) q.put(3,6) q.put(2,7) q.put(1,8) while not q.empty(): item = q.get()[1] print item, print
@Ruturaj what error ? Edit your question and add your error and your code. Also are you sure that your queue is actually a PriorityQueue and not something else ?
Items are not necessarily tuples of the form (priority, data). Items may be any comparable object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.