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

Brian van den Broek brian.van.den.broek at gmail.com
Wed May 9 02:48:18 CEST 2012

```On 8 May 2012 23:23, Jacob Bender <benderjacob44 at gmail.com> wrote:
> Dear Tutors,
>
>
> "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."
>
> And here's my source code:

<snip>

> 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
> list as described in my original email. Also, I do thank you for your
> original replies!
>
> --
> Thank you,
> Jacob

Hi Jacob,

While I agree with those who suggested you send some code, I didn't
look at it too closely. Only close enough to be fairly sure I wasn't
doing everything for you by suggesting you consider the following
approach :-)

>>> neurons = {0:{1:4, 2:5}, 1:{0:6, 2:1}, 2:{0:3, 1:1}}
>>> weights = {}
>>> for neuron in neurons:
total_weight = 0
conections = neurons[neuron]
for conection in conections:
total_weight += conections[conection]
weights[neuron] = total_weight

>>> for neuron in sorted(weights):
print neuron, weights[neuron]

0 9
1 7
2 4
>>>

HTH,

Brian vdB
```