Dictionary creation in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we create a dictionary in Python, it is important to know how the time to build it grows as we add more items.
We want to understand how the work changes when the number of items increases.
Analyze the time complexity of the following code snippet.
my_dict = {}
for i in range(n):
my_dict[i] = i * 2
This code creates a dictionary by adding n key-value pairs, where each key is a number and the value is twice that number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding one item to the dictionary inside the loop.
- How many times: This happens once for each number from 0 up to n-1, so n times.
As we increase n, the number of times we add items grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows in a straight line as n grows. Double n, double the work.
Time Complexity: O(n)
This means the time to create the dictionary grows directly with the number of items we add.
[X] Wrong: "Adding each item to a dictionary takes longer and longer as the dictionary grows."
[OK] Correct: Python dictionaries are designed to add items quickly, so each addition takes about the same time regardless of size.
Understanding how dictionary creation scales helps you explain how data structures behave in real programs, a useful skill in many coding discussions.
"What if we used a list of tuples and converted it to a dictionary all at once? How would the time complexity change?"
Practice
Solution
Step 1: Understand dictionary syntax
Dictionaries in Python are created using curly braces{}.Step 2: Identify the empty dictionary
An empty dictionary is represented as{}, not square brackets, parentheses, or quotes.Final Answer:
my_dict = {} -> Option CQuick Check:
Empty dictionary = {} [OK]
- Using [] which creates a list, not a dictionary
- Using () which creates a tuple, not a dictionary
- Using '' which creates an empty string
Solution
Step 1: Check dictionary key-value pair syntax
Dictionary pairs use colon:between key and value inside curly braces.Step 2: Identify correct syntax
my_dict = {'a':1, 'b':2} uses curly braces and colons correctly. Options A and C use wrong brackets, and D uses equals sign which is invalid.Final Answer:
my_dict = {'a':1, 'b':2} -> Option DQuick Check:
Dictionary pairs use : inside {} [OK]
- Using square brackets [] instead of curly braces {}
- Using parentheses () instead of curly braces {}
- Using equals sign = instead of colon :
my_dict = {1: 'one', 2: 'two', 3: 'three'}
print(my_dict[2])Solution
Step 1: Understand dictionary key lookup
Accessingmy_dict[2]retrieves the value for key 2.Step 2: Find value for key 2
Key 2 maps to the string 'two' in the dictionary.Final Answer:
'two' -> Option AQuick Check:
my_dict[2] = 'two' [OK]
- Confusing keys and values
- Expecting the key itself as output
- Mistaking KeyError when key exists
my_dict = {1: 'one', 2: 'two', 3: 'three'}
print(my_dict[4])Solution
Step 1: Check dictionary keys
The dictionary has keys 1, 2, and 3 only.Step 2: Accessing a missing key
Trying to accessmy_dict[4]causes a KeyError because key 4 is not present.Final Answer:
Key 4 does not exist in the dictionary -> Option AQuick Check:
Accessing missing key causes KeyError [OK]
- Assuming all keys exist
- Confusing syntax error with runtime error
- Thinking keys must be strings
keys = ['name', 'age', 'city'] and values = ['Alice', 30, 'NY']. Which code correctly creates this dictionary?Solution
Step 1: Understand dictionary creation from two lists
We need to pair each key with its corresponding value by index.Step 2: Analyze options
my_dict = {keys[i]: values[i] for i in range(len(keys))} uses dictionary comprehension with index to pair keys and values correctly. my_dict = dict(keys, values) is invalid syntax. my_dict = {keys: values} creates a dictionary with one key (the list) which is invalid. my_dict = dict(zip(values, keys)) reverses keys and values.Final Answer:
my_dict = {keys[i]: values[i] for i in range(len(keys))} -> Option BQuick Check:
Use dict comprehension with index to pair keys and values [OK]
- Using dict() with two lists directly
- Swapping keys and values in zip()
- Using list as a key
