# This example provides a way to sort a list of dictionaries by multiple keys with a natural sort # This can be very useful if you need to sort a result set from a database on more than one column # Thanks to Ned Batchelder for the natural sort part import re def tryint(s): try: return int(s) except: return s def alphanum_key(s): """ Turn a string into a list of string and number chunks. "z23a" -> ["z", 23, "a"] """ return [tryint(c) for c in re.split('([0-9]+)', s)] my_data = [{'first_name': 'Robert', 'last_name': 'Smith', 'alphanum': 'g1'}, {'first_name': 'John', 'last_name': 'Doe', 'alphanum': 'g1'}, {'first_name': 'Jane', 'last_name': 'Doe', 'alphanum': 'g10'}, {'first_name': 'Jack', 'last_name': 'Sparrow', 'alphanum': 'g2'}] # We want to sort by 'alpha' ascending, then by 'last name' ascending # for descending, change reverse to True sort_list = [{'field': 'alphanum', 'reverse': False}, {'field': 'last_name', 'reverse': False}] # because Python's sort is stable, we need to reverse the list to get the correct sorting priority # of course, we could just create our sort_list in reverse order to begin with :-) sort_list = sort_list[::-1] for item in sort_list: my_data.sort(reverse=item['reverse'], key=lambda x: alphanum_key(x[item['field']])) for data in my_data: print 'first_name: ' + data['first_name'] + '\tlast_name: ' + data['last_name'] + '\talphanum: ' + data['alphanum'] + '\n'
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question