Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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
like image 763
knub Avatar asked Jan 11 '16 09:01

knub


People also ask

Can a dictionary key be a range?

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.

Can a range be a key in dictionary Python?

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.

Can a dictionary have a set as a key?

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.

Can a Key have multiple values in a dictionary?

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.


1 Answers

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

like image 181
James Avatar answered Sep 22 '22 17:09

James