Skip to content Skip to sidebar Skip to footer

Dictionary With Range As Key

In Python, how can I map from a range of values to one concrete value? Basically, I want a dictionary, which I can fill with ranges and index with numbers: rd = rangedict() rd[(0,

Solution 1:

You could use an interval tree

pip install intervaltree

from intervaltree import Interval, IntervalTree
rd = IntervalTree()

rd[0:10] = 5print rd[4]
print rd[5]

https://pypi.python.org/pypi/intervaltree

Solution 2:

Thanks to the comments I could find a solution using the intervaltree package.

from intervaltree import IntervalTree

tree = IntervalTree()
tree.addi(0, 10, 5)
print tree[4]
print tree[6]

# need to chop before, as the library stores both intervals otherwise
tree.chop(5, 15)
tree.addi(5, 15, 20)
print tree[4]
print tree[6]

Post a Comment for "Dictionary With Range As Key"