How do I sort dicts in Python with standard library only?

In Python, you can sort dictionaries using the built-in `sorted()` function along with some dictionary methods. The `sorted()` function allows you to sort based on keys or values. Here's how you can do it:

# Example of sorting a dictionary by key my_dict = {'apple': 3, 'banana': 1, 'cherry': 2} sorted_by_key = dict(sorted(my_dict.items())) print(sorted_by_key) # Output: {'apple': 3, 'banana': 1, 'cherry': 2} # Example of sorting a dictionary by value sorted_by_value = dict(sorted(my_dict.items(), key=lambda item: item[1])) print(sorted_by_value) # Output: {'banana': 1, 'cherry': 2, 'apple': 3}

Python sort dictionary sorted function sort by key sort by value