Compare keys() with sorted()
In the previous step, you learned how to use the sorted()
function with the keys()
method to iterate through a dictionary in sorted order. In this step, we'll delve deeper into the differences between using keys()
directly and using sorted()
with keys()
. Understanding these differences is crucial for writing efficient and readable Python code.
The keys()
method returns a view object, which is a dynamic view of the dictionary's keys. This means that if the dictionary changes, the view object reflects those changes. However, the view object itself is not a list and doesn't support sorting directly.
On the other hand, the sorted()
function returns a new list containing all items from the iterable in ascending order. When you use sorted(my_dict.keys())
, you're creating a new sorted list of the dictionary's keys, leaving the original dictionary and its view object unchanged.
Let's illustrate this with an example. Open the sort_keys.py
file in your ~/project
directory using the VS Code editor and modify it as follows:
## Create a dictionary
my_dict = {"b": 2, "a": 1, "c": 3}
## Get the keys view object
keys_view = my_dict.keys()
## Print the keys view object
print("Keys view object:", keys_view)
## Print the sorted keys
sorted_keys = sorted(my_dict.keys())
print("Sorted keys:", sorted_keys)
## Modify the dictionary
my_dict["d"] = 4
## Print the keys view object again
print("Keys view object after modification:", keys_view)
## Iterate through the dictionary using the sorted keys
for key in sorted_keys:
print(f"Key: {key}, Value: {my_dict[key]}")
In this code:
- We create a dictionary called
my_dict
.
- We get the keys view object using
my_dict.keys()
and store it in the keys_view
variable.
- We print the
keys_view
object and the sorted_keys
list.
- We then modify the dictionary by adding a new key-value pair.
- We print the
keys_view
object again to show that it reflects the changes in the dictionary.
- Finally, we iterate through the
sorted_keys
list and print the key-value pairs. Note that the sorted_keys
list remains unchanged, and does not reflect the addition of the key "d"
.
Now, run the script using the following command:
python sort_keys.py
You should see the following output:
Keys view object: dict_keys(['b', 'a', 'c'])
Sorted keys: ['a', 'b', 'c']
Keys view object after modification: dict_keys(['b', 'a', 'c', 'd'])
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
Observe that:
- The
keys_view
object is a dynamic view of the dictionary's keys. When we modify the dictionary, the keys_view
object reflects the changes.
- The
sorted_keys
list is a static list containing the keys at the time it was created. It does not reflect the changes made to the dictionary later.
- The loop only iterates through the keys that were present when
sorted_keys
was created.
This example highlights the key difference between keys()
and sorted()
. keys()
provides a dynamic view, while sorted()
creates a static sorted list. Choose the appropriate method based on whether you need to reflect changes in the dictionary or work with a fixed set of sorted keys.