0

I would like to build a priority queue in python in which the queue contains different dictionaries with their priority numbers. So when a "get function" is called, the dictionary with the highest priority(lowest number) will be pulled out of the queue and when "add function" is called, the new dictionary will be added to the queue and sorted based on its priority number.

Please do help out...

Thanks in advance!

3 Answers 3

6

Use the heapq module in the standard library.

You don't specify how you wanted to associate priorities with dictionaries, but here's a simple implementation:

import heapq

class MyPriQueue(object):
    def __init__(self):
        self.heap = []

    def add(self, d, pri):
        heapq.heappush(self.heap, (pri, d))

    def get(self):
        pri, d = heapq.heappop(self.heap)
        return d
Sign up to request clarification or add additional context in comments.

3 Comments

well i was hoping it could be in this format: if name == 'main': speech = Speak() firstDict = {'command_type': 'say_string','control_command':'stop','priority': 3 } secondDict = {'command_type': 'say_string','control_command':'resume','priority': 2 } thirdDict = {'command_type': 'say_wav','control_command': None, 'priority': 1 } #add the dictionaries to the global queue in speech and print them #using loop queue speech.add_to_queue(firstDict) speech.add_to_queue(secondDict) speech.add_to_queue(thirdDict) speech.loop_queue()
pls hw do i get code format so it appears like in a better way with the proper formatting. thanks!
@fabramma, you ask "how do I get code format": the answer is, put your code in your question, not in a comment! I suspect that's a deliberate design decision in SO: it pushes you to edit your question to make it clear and complete (code examples and everything), and to not veer off into long comment threads. Anyway, to make your code work, as opposed to just format nicely;-), see my answer to this question;-).
2

This is what I usually present as a side note in some of my patterns talks:

class PriorityQueue(object):
 def __init__(self, key=lambda x: x):
   self.l = []
   self.key = key
 def __len__(self):
   return len(self.l)
 def push(self, obj):
   heapq.heappush(self.l, (self.key(obj), obj))
 def pop(self):
   return heapq.heappop(self.l)[-1]

The OP's requirements are apparently to use operator.itemgetter('priority') as the key argument when instantiating PriorityQueue (needs an import operator at top of module, of course;-).

Comments

0

You can do this by adding a dict object to the class, and search it inside.

Comments

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.