Python: Elegant way of determining the nearest match for numbers in a dictionary
<p>I have a dictionary structure that maps an id (integer) into a number (double). The numbers are actually weights of an item.</p>

<p>I am writing a function that will allows me to fetch the id of a given weight (if the weight is found in the dict, else, it will return the <strong>id</strong> of the next closest (i.e. nearest matching) weight.</p>

<p>This is what I have so far:</p>

<pre><code>def getBucketIdByValue(bucketed_items_dict, value):
    sorted_keys = sorted(bucketed_items_dict.keys())
    threshold = abs(bucketed_items_dict[sorted_keys[-2]] -bucketed_items_dict[sorted_keys[-1]]) # determine gap size between numbers

    # create a small dict containing likely candidates
    temp = dict([(x - value),x] for x in bucketed_items_dict.values() if abs(x - value) &lt;= threshold)
    print 'DEBUG: Deviations list: ', temp.keys()
    smallest_deviation = min(temp.keys()) if value &gt;= 0 else max(temp.keys()) # Not sure about this ?
    smallest_deviation_key = temp[smallest_deviation]
    print 'DEBUG: found bucketed item key:',smallest_deviation_key
    return smallest_deviation_key
</code></pre>

<p>I'm not sure the logic is actually correct (esp. where I obtain the smallest deviatioon). In any event, if even the logic is correct, this seems an overly complicated way of doing things. Is there a more elegant/pythonic way of doing this?</p>

<p>Off the top of my head, I think a more pythonic/elegant way would be to do something like passing a custom function to the <code>min</code> function - don't know if that is possible...</p>

<p><strong>[[Update]]</strong></p>

<p>I am running Python 2.6.5</p>
