How to Sort Dictionary in Python by Keys

1. Introduction

Sorting a dictionary by its keys is a common task in Python. It allows you to organize and represent dictionary data in a specific order. Python dictionaries are inherently unordered (though as of Python 3.7, insertion order is preserved), but there are ways to sort them for display or further processing.

Definition

Sorting a dictionary by keys means arranging the dictionary entries based on the order of the keys using some sorting criteria, typically in ascending or descending order.

2. Program Steps

1. Create a dictionary with unordered keys.

2. Use the sorted() function to sort the dictionary keys.

3. Create a new dictionary that is ordered by the sorted keys.

4. Print the sorted dictionary.

3. Code Program

# Create an unordered dictionary
my_dict = {'banana': 3, 'apple': 2, 'pear': 5, 'orange': 1}

# Sort the dictionary by keys
sorted_keys = sorted(my_dict.keys())

# Create a new dictionary with sorted keys
sorted_dict = {key: my_dict[key] for key in sorted_keys}

# Print the sorted dictionary
print(f"Dictionary sorted by keys: {sorted_dict}")

Output:

Dictionary sorted by keys: {'apple': 2, 'banana': 3, 'orange': 1, 'pear': 5}

Explanation:

1. my_dict is a dictionary with fruit names as keys and integers as values. The keys are in an unordered state.

2. sorted_keys uses the sorted() function to sort the keys of my_dict. The sorted() function returns a new list containing all keys in sorted order.

3. sorted_dict is a dictionary comprehension that iterates over sorted_keys, creating a new dictionary with the same keys in sorted order.

4. Each key from sorted_keys is used to get the corresponding value from my_dict, ensuring that the key-value pairs remain intact.

5. The print statement displays sorted_dict, showing the dictionary sorted by keys. The output confirms that the keys are now sorted alphabetically.

Comments