Write a Python code snippet to sort a dictionary based on its key.
- User
Write a Python code snippet to sort a dictionary based on its key.
Assistant
Here is the Python code to sort a dictionary by its keys.
In Python, dictionaries are insertion-ordered (as of Python 3.7). To sort them, we extract the items, sort them based on the key, and create a new dictionary.
# Sample unsorted dictionary my_dict = { 'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2 } # Sorting the dictionary by key # 1. my_dict.items() gets the key-value pairs. # 2. sorted() sorts them (defaulting to the first element, which is the key). # 3. dict() converts the sorted list of tuples back into a dictionary. sorted_dict = dict(sorted(my_dict.items())) # Print the result print("Original Dictionary:", my_dict) print("Sorted Dictionary: ", sorted_dict)