[Tutor] Sorting the parts of a dictionary into a list

Peter Otten __peter__ at web.de
Sun May 6 15:51:15 CEST 2012


Jacob Bender wrote:

> Dear tutors,
> 
> I'm trying to create a neural network program. Each neuron is in a
> dictionary and each of its connections and their strengths are in a nested
> dictionary. So {0:{1:4, 2:5}}, 1:{0:6}, 2:{1:2}} would mean that neuron 0
> is connected to neuron 1 with a strength of 4. And it also means that
> neuron 1 is connected to neuron 0 with a strength of 6.
> 
> The problem is that I'm working on a function that is supposed to add the
> total strengths of each neuron. So, for example, neuron 0's connections
> have a total strength of 9 (4+5). The other problem is getting all of the
> total strengths and ordering the neurons into a list. So, from the
> example, the list would be from [0,1,2] because zero has the greatest
> total strength of 9, then 1 with a total strength of 6 and so on. I've
> been working on this problem for at least 2 hours now and still haven't
> found anything close to a solution.

It is always a good idea to post the code you have -- if only to give as an 
idea of your abilities.
 
> Thank you and please help!

You need a function to calculate the total strength

def total_strength(neuron):
    # calculate and return total strength

You can then sort the dictionary keys:

connections = {0:{1:4, 2:5}, 1:{0:6}, 2:{1:2}}
neurons_by_strength = sorted(connections, key=total_strength)

To give you an idea how the key function works:

>>> sorted([3, -2, 1], key=abs) # abs() calculates the absolute value
[1, -2, 3]

Writing the body of the total_strength() function is not hard: look up the 
neuron in the connections dict and sum up the values of the inner dict.

Come back here should these hints not be sufficient to get you going. 
Remember to provide some code next time ;)



More information about the Tutor mailing list