Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary keys as set of numbers

I'd like to structure a dictionary in python whose keys are pairs of min/max values between 0 and 1. For instance:

myDict = {(0, .5): 'red', (.5, 1): 'orange'}

I'd like to be able to call entries in the dictionary with a number within the set [min, max).

>>> myDict[.464897]
'red'
>>> myDict[.5]
'orange'

I feel like there might be a nice, simple way to do this. It is elusive, though, as I am still in my python diapers.

like image 541
Hank Avatar asked Apr 13 '13 11:04

Hank


People also ask

Can Python dictionary keys be numbers?

The dictionary webstersDict used strings as keys in the dictionary, but dictionary keys can be any immutable data type (numbers, strings, tuples etc). Dictionary values can be just about anything (int, lists, functions, strings, etc).

Can dictionary keys be sets?

Dictionary is a unique collection in Python. It contains key-value pairs. Dictionary can also contain tuple, sets and lists.

Can you use sets as dictionary keys Python?

Sets being mutable are not hashable, so they can't be used as dictionary keys. On the other hand, frozen sets are hashable and can be used as keys to a dictionary.

Can Python dictionary keys have multiple values?

General Idea: In Python, if we want a dictionary to have multiple values for a single key, we need to store these values in their own container within the dictionary. To do so, we need to use a container as a value and add our multiple values to that container. Common containers are lists, tuples, and sets.


1 Answers

Assuming the intervals do not overlap, there are no gaps and they are sorted you use a binary search:

>>> keys = [0.5, 1] # goes from 0 to 1, specify end interval
>>> vals = ['red', 'orange']
>>> import bisect
>>> vals[bisect.bisect_right(keys, 0.464897)]
'red'
>>> vals[bisect.bisect_right(keys, 0.5)]
'orange'
like image 194
jamylak Avatar answered Oct 19 '22 06:10

jamylak