The sorted()
function takes a key=
parameter
newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
Alternatively, you can use operator.itemgetter
instead of defining the function yourself
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
For completeness, add reverse=True
to sort in descending order
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
Python 3.7+ or CPython 3.6
Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementation detail.
>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
or
>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Older Python
It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.
For instance,
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x
will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x
.
And for those wishing to sort on keys instead of values:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
In Python3 since unpacking is not allowed we can use
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])
If you want the output as a dict, you can use collections.OrderedDict
:
import collections
sorted_dict = collections.OrderedDict(sorted_x)
Best Answer
Your code is running into Divide by Zero Error. Try this to convince yourself:
It clearly emerges from the interactive session above that when
i
takes the value5001
in the for loop,f(x[i-1], w[i-1])
yieldsnan
. There are several solutions to this issue. For instance, in order to avoid NaN values you could check whether the denominator of the fraction returned byf()
is zero prior to perform the division. If it is, you should return a conventional value of your choice (for example0
) instead of the result of the division. The following snippet implements such approach though a conditional expression:Alternatively, you could disable run time warnings (but if you do so you need to be aware of the potential risks) by including this code in your script:
The proposed workarounds avoid the RuntimeWarning but don't get your code working as you expect. Indeed, the calculated solution
w
is a vector in which all the elements are zero. I guess the reason for your code not being working properly is that you missed to assignw[0]
an initial value different to0
.For example, if you simply add this line just before the for loop:
you get this (apparently meaningful) curve rather than a flat plot.
Hope this helps!