I want to order the items in a dictionary using various comparator functions.
Please see my example code below. It is the last part using cmpRatio function with sorted() that does not work. I am not sure what I am doing wrong. Thanks in advance for any idea!
mydict = { 'a1': (1,6),
'a2': (10,2),
'a3': (5,3),
'a4': (1,2),
'a5': (3,9),
'a6': (9,7) }
# sort by first element of the value tuple: WORKS
print sorted(mydict.iteritems(), key=lambda (k,v): v[0])
# sort by second element of the value tuple: WORKS
print sorted(mydict.iteritems(), key=lambda (k,v): v[1])
# THIS is what I can't get working:
def cmpRatio(x,y):
sx = float(x[0])/x[1]
sy = float(y[0])/y[1]
return sx < sy
# sort by sum of the elements in the value tuple: DOES NOT WORK
print sorted(mydict.iteritems(), key=lambda (k,v): v, cmp=cmpRatio)
Avoid
cmpfunctions where possible because they are slow. They have to be re-evaluated for each comparison. Using akeymakes it so the key only needs to be computed once.Also, you say you want to sort by the sum of the value items, yet you are sorting by the difference. Sum would look like:
As mentioned in other answers, for the purpose of really wanting to define a
cmpfunction, you are not returning the proper value (must be -1,0, or 1).But also if you are just using a lambda to get the value, you can replace that with
itemgetterwhich should be faster than a python-side function:If you are trying to store up sort operations, it would be much better to store the key functions: