[Tutor] Sorting the Parts of a Dictionary into a List

Dave Angel d at davea.name
Wed May 9 00:23:55 CEST 2012


On 05/08/2012 05:23 PM, Jacob Bender wrote:
> <SNIP>
>
>
>     def smartest(self): #Return the neurons in order from smartest to
> dumbest in list form.
>         for neuron in self.neurons:
>             sorted(neuron, key=self.total(neuron))
>
> The total function works when it returns the strength of a neuron, but I
> don't think the "sorted" function is the best because, with its current
> configuration, it returns a type error. I have been doing python for
> several years now. I don't know EVERYTHING there is to know, but I am able
> to do most tasks without error. Please help me get the neurons into an
> order in a list as described in my original email. Also, I do thank you for
> your original replies!
>
>
You put your error traceback in a separate thread.  Please use
reply(-all) to keep the related messages in one place.

Without trying to really understand the rest of the code, this last
function is messed up in many ways.  So I'll suggest something that
makes it plausible, but not necessarily what the rest of the code wants.

if you're going to sort something with sort() or sorted(), you don't do
that inside a loop.  You sort the list directly, in a single operation. 
And if you want to return something you need a return statement.  If
you're passing a key function into the sorted() function, you want to
pass the function object, not the result of calling it once (ie. omit
the parentheses).  So if you want to sort the neuron items in the
neurons list, you'd do something like:

     def smartest(self):
             return sorted(neurons, key=self.total)



-- 

DaveA



More information about the Tutor mailing list