2

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'])
]
"""
2
Contributors
1
Reply
3
Views
8 Years
Discussion Span
Last Post by Ene Uran
1

Here is the code to sort a dictionary of dictionaries:

# 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
"""
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.