Custom Sorting Algorithms in Python

3 Jan 2010

Today I am writing some sorting algorithms, and I guess I must always do this in javascript because I realized I did not really know how to do this in python. Anyway, it is pretty simple.

I am sorting a list of dicts, and I assigned each item a ‘weight’ attribute based on a number of other properties of the dict. Once each dict has a weight, I use the following function to sort the list.

def weight_compare(a, b):

x = a.get('weight', 0)
y = b.get('weight', 0)
if x > y:
    return 1
elif x==y:
    return 0
else:
    return -1

a = [{‘weight’: 2}, {‘weight’: 4}, {‘weight’: 1}]

a.sort(weight_compare)

a [{‘weight’: 1}, {‘weight’: 2}, {‘weight’: 4}]

a.sort(weight_compare, reverse=True)

a [{‘weight’: 4}, {‘weight’: 2}, {‘weight’: 1}]

Let's talk

I'm one of the founders of Venmo. If you liked this essay/experiment -- or didn't -- @ me.