Python sort a list by two values
Question: I'm trying to sort this list first by name in reverse. Then, after the first
set of results (where flag = "ZAR"), I want to sort the remaining elements by
time not in reverse:

    
    
    import operator
    list = [
        {"flag":"ZAR", "time":"17:45"},
        {"flag":"AUS", "time":"17:30"},
        {"flag":"AUS", "time":"17:15"},
        {"flag":"USA", "time":"17:00"},
        {"flag":"GBP", "time":"16:55"},
        {"flag":"ZAR", "time":"16:45"},
        {"flag":"USA", "time":"16:35"},
        {"flag":"GBP", "time":"16:25"},
        {"flag":"ZAR", "time":"16:15"},
    ]
    
    list.sort(key=operator.itemgetter("time"))
    list.sort(key=operator.itemgetter("flag"),reverse=True)
    
    
    print list
    
    [{'flag': 'ZAR', 'time': '16:15'}, {'flag': 'ZAR', 'time': '16:45'}, {'flag': 'ZAR', 'time': '17:45'}, {'flag': 'USA', 'time': '16:35'}, {'flag': 'USA', 'time': '17:00'}, {'flag': 'GBP', 'time': '16:25'}, {'flag': 'GBP', 'time': '16:55'}, {'flag': 'AUS', 'time': '17:15'}, {'flag': 'AUS', 'time': '17:30'}]
    

As you can see the flag sort was done correctly, but the other elements are
only sorted by time within the sorted country.

What I want is to always have the ZAR first and after that it does not matter
what the flag name is, only the time. So it should give this result:

    
    
    [{'flag': 'ZAR', 'time': '16:15'}, {'flag': 'ZAR', 'time': '16:45'}, {'flag': 'ZAR', 'time': '17:45'}, {'flag': 'GBP', 'time': '16:25'}, {'flag': 'USA', 'time': '16:35'}, {'flag': 'GBP', 'time': '16:55'}, {'flag': 'USA', 'time': '17:00'}, {'flag': 'AUS', 'time': '17:15'}, {'flag': 'AUS', 'time': '17:30'}]
    

How would this be done?


Answer: Amend your code to:

    
    
    import operator
    data = [
        {"flag":"ZAR", "time":"17:45"},
        {"flag":"AUS", "time":"17:15"},
        {"flag":"USA", "time":"17:00"},
        {"flag":"GBP", "time":"16:55"},
        {"flag":"ZAR", "time":"16:45"},
        {"flag":"USA", "time":"16:35"},
        {"flag":"GBP", "time":"16:25"},
        {"flag":"ZAR", "time":"16:15"},
    ]
    
    data.sort(key=operator.itemgetter("time"))
    data.sort(key=lambda L: L['flag'] == 'ZAR', reverse=True)
    
    # [{'flag': 'ZAR', 'time': '16:15'}, {'flag': 'ZAR', 'time': '16:45'}, {'flag': 'ZAR', 'time': '17:45'}, {'flag': 'GBP', 'time': '16:25'}, {'flag': 'USA', 'time': '16:35'}, {'flag': 'GBP', 'time': '16:55'}, {'flag': 'USA', 'time': '17:00'}, {'flag': 'AUS', 'time': '17:15'}, {'flag': 'AUS', 'time': '17:30'}]
    

