Iterating over dictionary keys in a sorted order allows you to traverse the keys in a predictable and organized manner. In this blog post, we will explore different methods to iterate over dictionary keys in sorted order in Python.
Method 1: Using the sorted() function
my_dict = {"c": 3, "a": 1, "b": 2} sorted_keys = sorted(my_dict.keys()) print("Sorted Keys:") for key in sorted_keys: print(key)
Output:
Sorted Keys:
a
b
c
Method 2: Using the sorted() function with a lambda function
my_dict = {"c": 3, "a": 1, "b": 2} sorted_keys = sorted(my_dict.keys(), key=lambda x: x.lower()) print("Sorted Keys:") for key in sorted_keys: print(key)
Output:
Sorted Keys:
a
b
c