Skip to content

Instantly share code, notes, and snippets.

@pythonhacker
Last active January 8, 2026 09:57
Show Gist options
  • Select an option

  • Save pythonhacker/bd033a502e23ddf38322c2c8a70ff108 to your computer and use it in GitHub Desktop.

Select an option

Save pythonhacker/bd033a502e23ddf38322c2c8a70ff108 to your computer and use it in GitHub Desktop.
A custom range dictionary using bisect
class RangeDict(dict):
""" A dictionary mapping a key to a range of integers """
def __getitem__(self, key):
sorted_keys = sorted(self.keys())
idx = bisect.bisect_right(sorted_keys, key)
# Mapped key is one down from index but we don't
# want to cycle using negative indices
if idx > 0: idx -= 1
mapped_key = sorted_keys[idx]
return super().__getitem__(mapped_key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment