Is it possible to do something like:
r = {range(0, 100): 'foo', range(100, 200): 'bar'}
print r[42]
> 'foo'
So I would like to use a numeric range as part of a dictionary index. To make things more complicated I would also like to use multi-indexes like ('a', range(0,100))
. So the concept should be ideally expandable to that. Any suggestions?
A similar question was asked as here, but I am interested in a comprehensive implementation as opposed to the different approaches of that question.
Answer #2: 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.
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
Use copy()This is a built-in Python function that can be used to create a shallow copy of a dictionary. This function takes no arguments and returns a shallow copy of the dictionary. When a change is made to the shallow copy, the original dictionary will remain unchanged.
As an alternative approach, if you are trying to look up values associated with certain ranges you could use the built in Python bisect
library as follows:
import bisect
def boundaries(num, breakpoints=[100, 200], result=['foo', 'bar']):
i = bisect.bisect(breakpoints, num-1)
return result[i]
print boundaries(42)
This would display:
foo
If you are on Python 3.x you can use a range
object as key but to retrieve a value you will do something like this:
In [33]: r = {range(0, 100): 'foo', range(100, 200): 'bar'}
In [34]: { r[key] for key in r if 42 in key}
Out[34]: {'foo'}
The reason you can't do this in Python2.x is because the range
function in version 2.7 onwards returns a list and lists cannot be used as dictionary keys because they do not provide a valid __hash__
method.
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