Heapdict

1.0.1 · maintenance · verified Wed Apr 15

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

Install

Imports

Quickstart

This example demonstrates how to create a `heapdict`, add items with associated priorities, peek at the lowest priority item, pop the lowest priority item, and efficiently change an item's priority.

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}")

view raw JSON →