0
0
Pythonprogramming~5 mins

Creating dictionary from two sequences in Python - Performance & Efficiency

Choose your learning style9 modes available
Time Complexity: Creating dictionary from two sequences
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the lists get longer, the number of pairs to process grows the same way.

Input Size (n)Approx. Operations
10About 10 pairs processed
100About 100 pairs processed
1000About 1000 pairs processed

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the dictionary grows in a straight line with the number of items.

Common Mistake

[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.

Interview Connect

Understanding how dictionary creation scales helps you explain efficiency clearly and shows you know how data structures behave with bigger inputs.

Self-Check

"What if we used a nested loop to pair keys and values instead of zip? How would the time complexity change?"