Created
June 1, 2012 04:11
-
-
Save psobot/2848702 to your computer and use it in GitHub Desktop.
Rounded Dictionary Access in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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