Python dictionary keys as set of numbers
Asked Answered
I

1

6

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.

Instinctive answered 13/4, 2013 at 11:18 Comment(0)
S
11

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'
Staton answered 13/4, 2013 at 11:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.