help - iter & dict

Justin Azoff justin.azoff at gmail.com
Thu Aug 3 16:56:32 EDT 2006


aking at mappi.helsinki.fi wrote:
> Im trying to iterate through values in a dictionary so i can find the
> closest value and then extract the key for that value....what ive done so far:
[snip]
> short time. I was trying to define a function (its my first!) so that i
> could apply to several 'dictionary's and 'exvalue's.
[snip]

If you plan on searching a single dictionary for many values, it may be
much faster to convert the dictionary into a sorted list, and use the
bisect module to find the closest value...

something like:

import bisect

class closer_finder:
    def __init__(self, dataset):
        self.dataset = dataset
        flat = [(k,v) for v,k in dataset.iteritems()]
        flat.sort()
        self.flat = flat

    def __getitem__(self, target):
        flat = self.flat
        index = bisect.bisect_right(flat, (target, ))

        #simple cases, smaller than the smaller,
        #or larger than the largest
        if index == 0:
            v,k = flat[0]
            return k,v
        elif index == len(flat):
            v,k = flat[-1]
            return k,v

        #otherwise see which of the neighbors is closest.
        leftval, leftkey   = flat[index-1]
        rightval, rightkey = flat[index]

        leftdiff  = abs(leftval - target)
        rightdiff = abs(rightval - target)

        if leftdiff <= rightdiff:
            return leftkey, leftval
        else:
            return rightkey, rightval

In [158]:sample_data
Out[158]:{'a': 1, 'c': 6, 'b': 3}

In [159]:d=closer_finder(sample_data)

In [160]:d.flat
Out[160]:[(1, 'a'), (3, 'b'), (6, 'c')]

In [161]:d[4]
Out[161]:('b', 3)

-- 
- Justin




More information about the Python-list mailing list