I wish to hold a heap of objects, not just numbers. They will have an integer attribute in them that the heap can sort by. The easiest way to use heaps in python is heapq,
Unfortunately, you can't, although this is an often requested feature.
One option would be to insert (key, value) tuples into the heap. However, that won't work if the values throw an exception when compared (they will be compared in the case of a tie between keys).
A second option would be to define a __lt__
(less-than) method in the class that will use the appropriate attribute to compare the elements for sorting. However, that might not be possible if the objects were created by another package or if you need them to compare differently elsewhere in the program.
A third option would be to use the sortedlist class from the blist module (disclaimer: I'm the author). The constructor for sortedlist
takes a key
parameter that lets you specify a function to return the sort key of an element, similar to the key
parameter of list.sort
and sorted
.