435,635 Members | 2,227 Online + Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,635 IT Pros & Developers. It's quick & easy.

help - iter & dict

 P: n/a Dear Python people, im a newbie to python and here...so hello! 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: def pcloop(dictionary, exvalue): z = dictionary.itervalues() y = z - exvalue v = (y*y)**1/2 if v < 0.001: u = dictionary.get[z] return u ive been working off a couple of books and this is the best i can get it in short time. I was trying to define a function (its my first!) so that i could apply to several 'dictionary's and 'exvalue's. The best ive been able to come up with is iterating over the dictionary values, subtracting the exvalue, squaring then root squaring to render positive and applying an error (0.001) which is not the ideal solution i want. Is there any easy way to iterate through dictionary values and return the key for the minimum. Or can someone tell me where im going wrong with this def & loop. regards all Ali Aug 3 '06 #1
3 Replies

 P: n/a ak***@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 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 :sample_data Out:{'a': 1, 'c': 6, 'b': 3} In :d=closer_finder(sample_data) In :d.flat Out:[(1, 'a'), (3, 'b'), (6, 'c')] In :d Out:('b', 3) -- - Justin Aug 3 '06 #2 