Dictionary keys, values, and items in Python - Time & Space Complexity
When we use dictionary methods like keys(), values(), and items(), it is important to know how the time to get these collections changes as the dictionary grows.
We want to understand how long it takes to access these parts of a dictionary as it gets bigger.
Analyze the time complexity of the following code snippet.
my_dict = {i: i*2 for i in range(n)}
keys_list = list(my_dict.keys())
values_list = list(my_dict.values())
items_list = list(my_dict.items())
This code creates a dictionary with n items, then makes lists of its keys, values, and key-value pairs.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Iterating over all dictionary entries to collect keys, values, or items.
- How many times: Once for each element in the dictionary, so n times.
As the dictionary size grows, the time to get keys, values, or items grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: The work grows in a straight line with the number of items.
Time Complexity: O(n)
This means the time to get all keys, values, or items grows directly with the number of entries in the dictionary.
[X] Wrong: "Getting keys, values, or items is instant no matter the dictionary size."
[OK] Correct: Although the dictionary stores data efficiently, collecting all keys or values requires looking at each entry once, so it takes longer as the dictionary grows.
Understanding how dictionary methods scale helps you explain your code's efficiency clearly and shows you know how data size affects performance.
What if we only accessed a single key or value instead of all keys or values? How would the time complexity change?