help - iter & dict

Tim Chase python.list at tim.thechases.com
Thu Aug 3 16:19:17 EDT 2006


> 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


I think I understand what you're trying to do...given a target 
value, find the key/value pair in your dictionary where your 
value is closest to the target...where "closest" is defined by 
absolute-value difference between the target and the value.

Below I've included two such functions that do about the same 
thing (the difference being kind behavior in the first if the 
dataset is an empty dictionary, compared to just blowing up as 
the second one does).  The first findClosest function is verbose, 
but helps you understand what it's doing.  The second is, um, 
more succinct (read "deathly near opaque, and would probably get 
you shot for using it in a production environment").

Both return a tuple containing the key into the dataset and its 
associated value.

-tkc


def findClosest(dataset, target):
	closest_value = None
	closest_key = None
	closest_distance = None
	for k,v in dataset.items():
		distance = (target - v) ** 2
		if closest_value:
			if distance < closest_distance:
				closest_key = k
				closest_value = v
				closest_distance = distance
		else:
			closest_key = k
			closest_value = v
			closest_distance = distance
	return closest_key, closest_value

def findClosest2(dataset, target):
	return reduce(
		lambda x,y:
		((target - y[1]) ** 2 <
		(target - x[1]) ** 2)
		and y or x, dataset.items())

if __name__ == '__main__':
	sample_data = {'a':1,
		'b':3,
		'c':6}

	target = 4
	print findClosest(sample_data, target)
	print findClosest2(sample_data, target)



More information about the Python-list mailing list