Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a range as a dictionary index in Python [duplicate]

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.

like image 800
n1000 Avatar asked Feb 09 '16 08:02

n1000


People also ask

Can I put a range in a dictionary Python?

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.

Can there be duplicate in dictionary Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can dictionary have duplicate key values?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Does copy () work on dictionaries in Python?

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.


Video Answer


2 Answers

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
like image 138
Martin Evans Avatar answered Oct 09 '22 15:10

Martin Evans


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.

like image 29
styvane Avatar answered Oct 09 '22 15:10

styvane