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, 10)] = 5
print rd[4] # prints 5
print rd[6] # prints 5
rd[(5, 15)] = 20
print rd[4] # prints 5
print rd[6] # prints 20
Yes, you can, only if you convert your range lists as immutable tuple , so they are hashable and accepted as keys of your dictionary: stealth_check = { tuple(range(1, 6)) : 'You are about as stealthy as thunderstorm.
Use ranges as key in dict, and the dict can be accessed by the number within the range, and get the value the range mapping to. The looking up time on average is O(M) where M is the number of range keys in the dictionary.
However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable. Values, on the other hand, can be any type and can be used more than once.
In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.
You could use an interval tree
pip install intervaltree
from intervaltree import Interval, IntervalTree
rd = IntervalTree()
rd[0:10] = 5
print rd[4]
print rd[5]
https://pypi.python.org/pypi/intervaltree
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With