help - iter & dict

aking at mappi.helsinki.fi aking at mappi.helsinki.fi
Thu Aug 3 17:42:00 EDT 2006


Quoting taleinat <taleinat at gmail.com>:

> 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]
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

I know im a little bit over my head here but have survived up until now by
books and debugging before the code runs. before last week the most lines of
code ive written are .....4.

Yes i think i can stick to simplest to understand for now and work round at
a different time.


Ive tried the code:

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

    Cpcb = input("\n\nPlease enter the carbon percentage value obtained from
the microanalysis. If none, enter 0: ")
    print"\n\nCellulose Carbon Percentage is " + `Cpca` + "\n\nMaximum
potential monomer carbon weight is " + `Cwmax` + "\n\nMaximum potential
carbon percentage is " + `Cpcmax` + "\n\nPercentage difference between
Cellulose and Maximum is " + `Cdiff` + "\n\n"
    CDS = findClosest(CDSitdict, Cpcb)
    print("\nThe DS value based on carbon content is " + `CDS` + "\n\n")


here is a sample of the dictionary (normally 1000 iterations in there, all
non zero and to 15 decimal places) and the sample value:

Cpcb = 33.94

CDSitdict = {28.473823598317392: "'2.4869999999999832'", 40.06163037274758:
"'0.2910000000000002'", 27.756248559438422: "'2.8349999999999964'",
33.2299196586726: "'1.1249999999999962'", 29.989685187220061:
"'1.9139999999999677'", 31.502319473614037: "'1.490999999999983'",
28.487341570327612: "'2.480999999999983'", 30.017763818271245:
"'1.9049999999999681'", 32.943466663842266: "'1.1789999999999943'",
30.520103712886584: "'1.7519999999999736'", 31.453205956498341:
"'1.5029999999999826'", 29.484222697359598: "'2.084999999999968'",
28.413513489228706: "'2.5139999999999842'", 28.314852455260802:
"'2.558999999999986'", 28.652931545003508: "'2.4089999999999803'"}


heres the error i get after entering Cpcb

Traceback (most recent call last):
  File "elementalDS.py", line 156, in ?
    CDS = findClosest(CDSitdict, Cpcb)
  File "elementalDS.py", line 142, in findClosest
    distance = (target - v) ** 2
TypeError: unsupported operand type(s) for -: 'float' and 'str'
alicat at linux:~/Desktop>

i also tried to format the key in the dictionary from a number to a string
with single quotes but formatting with %s didnt work so i have used

itera = "\'" + `DSit` + "\'"
CDSitdict[Cpcmax] = itera

?

maybe i can return the favours someday...lol

a



More information about the Python-list mailing list