Creating dictionary from two sequences in Python - Performance & Efficiency
When we create a dictionary from two lists, we want to know how the time it takes grows as the lists get bigger.
We ask: How does the work change when the number of items increases?
Analyze the time complexity of the following code snippet.
keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3, 4]
dictionary = {k: v for k, v in zip(keys, values)}
This code pairs each key with a value to make a dictionary.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through both lists together using
zip. - How many times: Once for each pair of items, so as many times as the length of the shorter list.
As the lists get longer, the number of pairs to process grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 pairs processed |
| 100 | About 100 pairs processed |
| 1000 | About 1000 pairs processed |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to create the dictionary grows in a straight line with the number of items.
[X] Wrong: "Creating a dictionary from two lists takes the same time no matter how big the lists are."
[OK] Correct: Actually, the time depends on how many pairs you combine. More items mean more work.
Understanding how dictionary creation scales helps you explain efficiency clearly and shows you know how data structures behave with bigger inputs.
"What if we used a nested loop to pair keys and values instead of zip? How would the time complexity change?"