Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
python: approaches to sort a list of dictionaries
#!/usr/bin/python
from __future__ import print_function
# from https://wiki.python.org/moin/SortingListsOfDictionaries
def multikeysort(items, columns):
from operator import itemgetter
comparers = [ ((itemgetter(col[1:].strip()), -1) if col.startswith('-') else (itemgetter(col.strip()), 1)) for col in columns]
def comparer(left, right):
for fn, mult in comparers:
result = cmp(fn(left), fn(right))
if result:
return mult * result
else:
return 0
return sorted(items, cmp=comparer)
if __name__ == "__main__":
a = {"key1": 5 , "key2": 8, "key3": 2}
b = {"key1": 7 , "key2": 4, "key3": 9}
c = {"key1": 6 , "key2": 1, "key3": 1}
masterList = [a, b, c]
sortedList = multikeysort(masterList, ['key1', 'key2', 'key3'])
keys = ('key1', 'key2', 'key3')
print("Original unsorted list:")
for i in masterList:
row = [ str(i[k]) for k in keys ]
print( "\t", "\t".join(row) )
print("Sorted list:")
for i in sortedList:
row = [ str(i[k]) for k in keys ]
print( "\t", "\t".join(row) )
# Another alternative approach (1)
# # Sort by multiple keys - case sensitive
# from operator import itemgetter
# mylist = sorted(mylist, key=itemgetter('name', 'age'))
# # Sort by multiple keys - case insensitive
# mylist = sorted(mylist, key=lambda k: (k['name'].lower(), k['age']))
# Another alternative approach (2)
# Schwartzian Transform in python
# sort_on = "key2"
# decorated = [(dict_[sort_on], dict_) for dict_ in undecorated]
# decorated.sort()
# result = [dict_ for (key, dict_) in decorated]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment