| | |
Sorting complicated objects (Python)
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
This code snippet shows you how to sort more complicated objects like a list of lists (or tuples) by selecting an index of the item to sort by.
# sorting a list of lists/tuples by index # tested with Python 2.5.4 and Python 3.1.1 by vegaseat import operator # in [[name1, score1], [name2, score2], ...] score is at index=1 score = operator.itemgetter(1) player_score = [['zoro', 88], ['jerry', 68], ['albert', 99]] # sort by decreasing score player_score.sort(key=score, reverse=True) print(player_score) """my result --> [['albert', 99], ['zoro', 88], ['jerry', 68]] """ print('-'*50) # sort a more complicated combination of lists/tuples: mylist = [ (1, ['a', '3.1', 'ad']), (2, ['b', '4.0', 'bd']), (3, ['c', '2.5', 'cd']), ] # sort by item at index [1][1] of each tuple in mylist # using a helper function like lambda newlist = sorted(mylist, key=lambda tup: tup[1][1]) print(newlist) """my result (made pretty) --> [ (3, ['c', '2.5', 'cd']), (1, ['a', '3.1', 'ad']), (2, ['b', '4.0', 'bd']) ] """ print('-'*50) # or ... # sort by item at index [1][1] of each tuple in mylist # use the Schwartzian transform algorithm # temporarily put a copy of indexed item in front templist = [(x[1][1], x) for x in mylist] templist.sort() # remove temporary front item after sorting newlist = [val for (temp, val) in templist] print(newlist) """my result (made pretty) --> [ (3, ['c', '2.5', 'cd']), (1, ['a', '3.1', 'ad']), (2, ['b', '4.0', 'bd']) ] """
0
•
•
•
•
Here is the code to sort a dictionary of dictionaries:
Python Syntax (Toggle Plain Text)
# sorted display of a dictionary of dictionaries def dict_of_dict_sort(dd, key): """ print out selected items from a dictionary of dictionaries dd sorted by a given key """ for k in sorted(dd, key=lambda x: dd[x][key]): print( k, dd[k]['age'], dd[k]['country'] ) user_dict = { 'Bill': {'age': 39, 'country': 'USA'}, 'Dave' : {'age': 26, 'country': 'Canada'}, 'Olaf' : {'age': 33, 'country': 'Sweden'} } # display sorted by age dict_of_dict_sort(user_dict, 'age') """my result --> Dave 26 Canada Olaf 33 Sweden Bill 39 USA """
Similar Threads
- Sorting a List of Class Objects by Obj Dictionary (Python)
- Confusing strings (Python)
- sort a list with python (Python)
- Code Snippet: Sorting Algorithms in Python (Python)
- Code Snippet: A List of Class Objects (Python) (Python)
- Removing elements from a list in a loop (Python)
- sorting through an array of objects (Java)
| Thread Tools | Search this Thread |
Tag cloud for Python
abrupt apache application argv beginner binary book calculator change cipher code command compile converter dictionaries dictionary dynamic event examples excel file float format ftp function google gui homework import inches input java keyboard launcher line linux list lists loop maze microphone mouse movingimageswithpygame newb number numbers obexftp output parsing path permissions phonebook plugin port prime program programming projects py2exe pygame pyqt python random recursion recursive refresh remote scrolledtext search session signal simple ssh string strings strip table terminal text thread threading time tkinter tlapse trick tuple tutorial ubuntu unicode unit urllib urllib2 valueerror variable verify vigenere windows wordgame wxpython xlwt



