Python sorted(dict) function


The sorted() function in Python can be used to return a new sorted list from the keys of a dictionary. This function is versatile and can sort data in various ways, but when applied to a dictionary, it primarily focuses on the keys.

Syntax

sorted_keys = sorted(dict)
  • dict: The dictionary whose keys you want to sort.

Return Value

  • The sorted() function returns a new list containing the keys of the dictionary sorted in ascending order by default. If the dictionary is empty, it returns an empty list.

Example

Here are some examples to illustrate how sorted() works with dictionaries:

1. Basic Example

# Example dictionary my_dict = {'banana': 3, 'apple': 2, 'orange': 1} # Using sorted() to sort the keys of the dictionary sorted_keys = sorted(my_dict) print(sorted_keys) # Output: ['apple', 'banana', 'orange']

2. Sorting with Custom Order

You can also use the key parameter to specify a custom sorting function. For example, if you want to sort the keys by their lengths:

# Example dictionary my_dict = {'banana': 3, 'apple': 2, 'kiwi': 5, 'orange': 1} # Sorting keys by their length sorted_keys_by_length = sorted(my_dict, key=len) print(sorted_keys_by_length) # Output: ['kiwi', 'apple', 'banana', 'orange']

3. Sorting in Descending Order

You can sort the keys in descending order by setting the reverse parameter to True:

# Example dictionary my_dict = {'banana': 3, 'apple': 2, 'orange': 1} # Sorting keys in descending order sorted_keys_desc = sorted(my_dict, reverse=True) print(sorted_keys_desc) # Output: ['orange', 'banana', 'apple']

Use Cases

  • Retrieving Ordered Keys: Useful when you need to process keys in a specific order without modifying the original dictionary.
  • Dynamic Sorting: Allows for sorting based on different criteria by using the key parameter, making it flexible for various applications.
  • Preparing for Iteration: Helps in preparing ordered iterations over the keys for consistent behavior in algorithms or outputs.

Summary

The sorted(dict) function provides an efficient way to retrieve the keys of a dictionary in a sorted order, returning a new list of sorted keys. It can be customized to sort based on different criteria and can sort in both ascending and descending orders. This function is valuable for managing dictionaries and ensuring that keys are processed in a predictable manner.