Skip to content

Instantly share code, notes, and snippets.

@psobot
Created June 1, 2012 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psobot/2848702 to your computer and use it in GitHub Desktop.
Save psobot/2848702 to your computer and use it in GitHub Desktop.
Rounded Dictionary Access in Python
class RoundingDict(dict):
def __getitem__(self, key):
if key in self:
return dict.__getitem__(self, key)
try:
values = [abs(x - key) for x in self.keys()]
return self.values()[values.index(min(values))]
except (TypeError, ValueError):
raise KeyError(key)
if __name__ == "__main__":
# Useful for storing sparse numeric lookup tables
x = RoundingDict({5: "Some low value...", 50: "Middle of the road.", 100: "Top end!"})
print "What's 22?"
print x[22]
print "What about 78?"
print x[78]
# Or, in my case, for storing audio samples:
velocity_map = RoundingDict({0: "snare_soft.wav", 64: "snare_med.wav", 127: "snare_loud.wav"})
print "What samples should I use for a snare roll?"
for velocity in xrange(0, 127, 10):
print velocity_map[velocity]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment