How to sort a dictionary first by value, then by key in Python

1 Answer

0 votes
from typing import Dict, TypeVar

K = TypeVar('K')
V = TypeVar('V')

def sort_map_by_value_then_key(source_map: Dict[K, V]) -> Dict[K, V]:
    """
    Sorts a dictionary first by value (ascending), then by key (ascending) as a tie-breaker.
    
    Args:
        source_map: The input dictionary to be sorted.
        
    Returns:
        A new dictionary containing the entries sorted by value then key.
    """
    # Sort items using a tuple key: item[1] is the value (primary), 
    # item[0] is the key (secondary tie-breaker)
    sorted_items = sorted(source_map.items(), key=lambda item: (item[1], item[0]))
    
    # Reconstruct the dictionary (Python 3.7+ preserves insertion order)
    return dict(sorted_items)

if __name__ == "__main__":
    # Initialize the dictionary with the requested values
    scores = {
        "Luna": 85,
        "Sofia": 92,
        "Charlie": 96,
        "Bella": 92,
        "Brock": 80,
        "Jolie": 96,
        "Bob": 92,
        "Eve": 92
    }

    # Sort the dictionary using our function
    sorted_scores = sort_map_by_value_then_key(scores)

    # Display the sorted results
    print("Sorted by value (score), then by key (name):")
    print("-" * 44)
    for name, score in sorted_scores.items():
        print(f"{name}: {score}")


'''
run:

Sorted by value (score), then by key (name):
--------------------------------------------
Brock: 80
Luna: 85
Bella: 92
Bob: 92
Eve: 92
Sofia: 92
Charlie: 96
Jolie: 96

'''

 



answered Oct 23 by avibootz
...