Sort a Dictionary by Key or Value in Python

Sorting a dictionary allows you to arrange its key-value pairs in a specific order. In this blog post, we will explore different methods to sort a dictionary by key or value in Python.

Method: Sorting by Key Using the sorted() Function

# Method 1: Sorting by Key Using the sorted() Function
my_dict = {"name": "John", "age": 30, "city": "New York"}
sorted_dict = {k: my_dict[k] for k in sorted(my_dict)}
print("Sorted dictionary by key:", sorted_dict)

Output:

Sorted dictionary by key: {‘age’: 30, ‘city’: ‘New York’, ‘name’: ‘John’}