Finding closest value in a dictionary
<p>I have a dictionary, <code>T</code>, with keys in the form <code>k,i</code> with an associated value that is a real number (float). Let's suppose I choose a particular key <code>a,b</code> from the dictionary <code>T</code> with corresponding value <code>V1</code>âwhat's the most efficient way to find the closest value to <code>V1</code> for a key that has the form <code>a+1,i</code>, where <code>i</code> is an integer that ranges from 0 to n? (<code>k</code>,<code>a</code>, and <code>b</code> are also integers.) To add one condition on the values of items in <code>T</code>, as <code>i</code> increases in the key, the value associated to <code>T[a+1,i]</code> is strictly increasing (i.e. <code>T[a+1,i+1] &gt; T[a+1,i]</code>).</p>

<p>I was planning to simply run a while loop that starts from <code>i = 0</code> and compares the value<code>T[a+1,i]</code> to <code>V1</code>. To be more clear, the loop would simply stop at the point at which <code>np.abs(T[a+1,i] - V1) &lt; np.abs(T[a+1,i+1] - V1)</code>, as I would know the item associated to <code>T[a+1,i]</code> is the closest to <code>T[a,b] = V1</code>. But given the strictly increasing condition I have imposed, is there a more efficient method than running a while loop that iterates over the dictionary elements? <code>i</code> will go from 0 to n where n could be an integer in the millions. Also, this process would be repeated frequently so efficiency is key. </p>

<p>I propose to use bisect module.</p>

<pre><code>import bisect
import numpy as np


t = np.array([[1.1, 2.0, 3.7],
              [3.5, 5.6, 7.8],
              [2.5, 3.4, 10.0]])


def find_closest(t, a, i):
    """
    &gt;&gt;&gt; find_closest(t, 0, 2)
    (1, 0)
    """
    v = t[a, i]
    b_index = bisect.bisect_right(t[a + 1], v)
    try:
        if t[a + 1][b_index] - v &gt; t[a + 1][b_index - 1] - v:
            b_index -= 1
    except IndexError:
        pass
    return a + 1, b_index
</code></pre>

python python-2.7 loops dictionary iteration