Skip to content

Instantly share code, notes, and snippets.

@naiquevin
Created August 29, 2012 03:49
Show Gist options
  • Save naiquevin/3506617 to your computer and use it in GitHub Desktop.
Save naiquevin/3506617 to your computer and use it in GitHub Desktop.
Multi Level sorting example in Python
#!/usr/bin/env python
## An alternative approach for sorting list of dicts by multiple
## levels of criteria
## Original example: http://sleepythread.blogspot.in/2012/08/sorting-hash-on-more-than-one-key-with.html
import pprint
pp = pprint.PrettyPrinter(indent=4)
def compare_two(p, q, direction='asc'):
if direction == 'desc':
p, q = q, p
if p < q:
return -1
elif p > q:
return 1
else:
return 0
def comparator(a, b):
cmp_age = compare_two(a['age'], b['age'])
if cmp_age != 0:
return cmp_age
cmp_height=compare_two(a['height'], b['height'], 'desc')
if cmp_height != 0:
return cmp_height
return compare_two(a['weight'], b['weight'])
students = [{'sno': 1, 'age': 10, 'weight': 130, 'height': 170},
{'sno': 2, 'age': 8, 'weight': 130, 'height': 170},
{'sno': 3, 'age': 8, 'weight': 110, 'height': 180},
{'sno': 4, 'age': 8, 'weight': 110, 'height': 170},
{'sno': 5, 'age': 7, 'weight': 130, 'height': 170}]
pp.pprint(sorted(students, cmp=comparator))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment