help - iter & dict

taleinat taleinat at gmail.com
Thu Aug 3 17:17:19 EDT 2006


Ali writes:

>> 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

First of all, your code was broken everywhere...

Unlike many other languages, Python is fun! Just fire up an interpreter
("python" at the command line should work) and start playing around and trying
stuff out. You would have quickly found that dictionary.itervalueS() return an
iterator object (which must be iterated over), that dictionaries can be accessed
either with brackets "[]" -or- with the .get() method, and more.

If you're learning from a book, try everything you learn out at least once in
the interpreter - that way you'll make sure you understand everything, and
understand the syntax much faster (since the interpreter will -explain- what
your syntax errors are).

Second, Python has a built-in abs() method which returns the absolute value of a
number - using it is simpler and more readable.


Tim Chase <python.list <at> tim.thechases.com> writes:

> 		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

This has a bug - if closest_value happens to be zero at some point, it would be
overriden by the next value no matter what, since "if closest_value" would be
false. You must explicitly check "if closest_value is not None:".

Also the code could be simplified:

		if closest_value is None or distance < closest_distance:
			closest_key = k
			closest_value = v
			closest_distance = distance

> 
> def findClosest2(dataset, target):
	if not dataset: # a dict is considered false if empty, true otherwise
		return (None,None)
> 	return reduce(
> 		lambda x,y:
> 		((target - y[1]) ** 2 <
> 		(target - x[1]) ** 2)
> 		and y or x, dataset.items())

I would advise everyone still learning the basics to completely ignore the
second function. Yes, it works, but this code is VERY confusing for a beginner,
both because of the reduce (tough to grasp) and because of the confusing and
bug-prone "and-or trick". (even though this is a classic use for reduce)

- Tal Einat
a='maciogaiea at l.ntmtl'[::-1]; print reduce(lambda m,x:[m[i]+s[-1] for i,s in
enumerate(sorted(m))],[list(a)]*len(a))[3]





More information about the Python-list mailing list