Heapdict
Heapdict is a Python library that implements a mutable mapping (like a dictionary) but with the properties of a min-heap. It provides efficient decrease-key and increase-key operations, making it particularly suitable for priority queue implementations in algorithms such as Dijkstra's or A*. Unlike Python's built-in `heapq` module, heapdict allows for efficient modification of item priorities. The current version is 1.0.1, with its last release in September 2019.
Warnings
- breaking Heapdict uses `collections.MutableMapping` which was deprecated in Python 3.8 and subsequently removed in Python 3.13. This causes an `AttributeError` when importing or using `heapdict` in Python 3.8+ (specifically 3.11, 3.12, 3.13 reported).
- gotcha Heapdict does not guarantee stable sorting for items with equal priorities. If multiple items have the same priority, their retrieval order is not guaranteed to be FIFO (First-In, First-Out), which differs from `heapq.nsmallest`.
- gotcha The project has not seen a new release since September 2019, and several open issues exist regarding compatibility with newer Python versions and potential minor bugs. This indicates limited active maintenance.
Install
-
pip install heapdict
Imports
- heapdict
from heapdict import heapdict
Quickstart
from heapdict import heapdict
# Create a new heapdict
hd = heapdict()
# Add items with priorities (key, priority)
hd['task_A'] = 5
hd['task_B'] = 1
hd['task_C'] = 10
print(f"Initial heapdict: {list(hd.items())}")
# Access the item with the lowest priority without removing it
lowest_priority_item = hd.peekitem()
print(f"Lowest priority item (peek): {lowest_priority_item}")
# Remove and return the item with the lowest priority
first_task, first_priority = hd.popitem()
print(f"Popped: {first_task} with priority {first_priority}")
print(f"Heapdict after pop: {list(hd.items())}")
# Change the priority of an existing item (decrease-key)
hd['task_C'] = 2 # task_C now has higher priority than task_A
print(f"Heapdict after changing task_C priority: {list(hd.items())}")
# Pop the next lowest priority item
second_task, second_priority = hd.popitem()
print(f"Popped: {second_task} with priority {second_priority}")