Sorting complicated objects (Python)

vegaseat 2 Tallied Votes 369 Views Share

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'])
]
"""
Ene Uran 638 Posting Virtuoso

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
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.