Your Page Title
🔍

    How to sort a dictionary in Python

    You can sort a dictionary in Python in different ways depending on what you want to sort by: keys or values. Since dictionaries in Python are inherently unordered (though they maintain insertion order since Python 3.7), you cannot directly “sort” a dictionary in place. Instead, you’ll typically create a new sorted structure (like a list of tuples or a new dictionary).

    Here’s a detailed explanation:

    1. Sorting by Keys

    If you want to sort a dictionary by its keys, you can use the sorted() function. This will return a sorted list of keys, values, or key-value pairs.

    Example:

    my_dict = {'b': 2, 'a': 5, 'c': 3}
    
    # Sorting by keys
    sorted_dict = dict(sorted(my_dict.items()))
    print(sorted_dict)

    Output:

    {'a': 5, 'b': 2, 'c': 3}

    Explanation:

    • my_dict.items() converts the dictionary into a list of tuples: [('b', 2), ('a', 5), ('c', 3)].
    • sorted() sorts this list by the keys (by default, that’s the first element of every tuple).
    • dict() converts the sorted list of tuples back into a dictionary.

    2. Sorting by Values

    To sort by the values, you can provide a custom sorting key to the sorted() function.

    Example:

    my_dict = {'b': 2, 'a': 5, 'c': 3}
    
    # Sorting by values
    sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
    print(sorted_dict)

    Output:

    {'b': 2, 'c': 3, 'a': 5}

    Explanation:

    • key=lambda item: item[1] tells sorted() to use the value (the second element of each tuple) for sorting.

    3. Sorting in Descending Order

    To sort in reverse (descending) order, add the reverse=True argument.

    Example (by keys):

    my_dict = {'b': 2, 'a': 5, 'c': 3}
    
    # Sorting by keys in descending order
    sorted_dict = dict(sorted(my_dict.items(), reverse=True))
    print(sorted_dict)

    Output:

    {'c': 3, 'b': 2, 'a': 5}

    Example (by values):

    my_dict = {'b': 2, 'a': 5, 'c': 3}
    
    # Sorting by values in descending order
    sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
    print(sorted_dict)

    Output:

    {'a': 5, 'c': 3, 'b': 2}

    4. Using collections.OrderedDict

    If you need to preserve the order of a sorted dictionary (especially when using versions of Python before 3.7), use collections.OrderedDict.

    Example:

    from collections import OrderedDict
    
    my_dict = {'b': 2, 'a': 5, 'c': 3}
    
    # Sorting by values
    sorted_dict = OrderedDict(sorted(my_dict.items(), key=lambda item: item[1]))
    print(sorted_dict)

    Output:

    OrderedDict([('b', 2), ('c', 3), ('a', 5)])

    5. Sorting Keys or Values Alone

    If you want to sort just the keys or values (without restructuring the dictionary), you can do so directly:

    Sort only keys:

    my_dict = {'b': 2, 'a': 5, 'c': 3}
    sorted_keys = sorted(my_dict.keys())
    print(sorted_keys)

    Sort only values:

    sorted_values = sorted(my_dict.values())
    print(sorted_values)

    Key Takeaways:

    1. sorted() returns a new sorted list: Dictionaries themselves are not modified in place.
    2. Sorting criteria:
      • By default, sorted() sorts by keys.
      • Use key=lambda item: item[1] to sort by values.
    3. Use reverse=True for descending order.
    4. In Python 3.7+, dictionaries preserve insertion order, so converting back to a dictionary after sorting will keep the sorted order.