Last active
January 8, 2026 09:57
-
-
Save pythonhacker/bd033a502e23ddf38322c2c8a70ff108 to your computer and use it in GitHub Desktop.
A custom range dictionary using bisect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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