0
0
Pythonprogramming~10 mins

Basic dictionary comprehension in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Basic dictionary comprehension
Start with iterable
Pick each item
Apply expression for key and value
Add key:value to dictionary
Repeat for all items
Return new dictionary
Dictionary comprehension creates a new dictionary by looping over items and applying expressions for keys and values.
Execution Sample
Python
numbers = [1, 2, 3]
squares = {x: x*x for x in numbers}
print(squares)
Creates a dictionary where keys are numbers and values are their squares.
Execution Table
Stepx (current item)Expression for keyExpression for valueDictionary state
1111{1: 1}
2224{1: 1, 2: 4}
3339{1: 1, 2: 4, 3: 9}
End---All items processed, dictionary complete
💡 All items in the list processed, comprehension ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
x-123-
squares{}{1: 1}{1: 1, 2: 4}{1: 1, 2: 4, 3: 9}{1: 1, 2: 4, 3: 9}
Key Moments - 2 Insights
Why does the dictionary update after each step instead of creating a list?
Because dictionary comprehension uses curly braces { } and key:value pairs, it builds a dictionary step-by-step as shown in the execution_table rows.
What happens if the key expression repeats the same value?
The dictionary will overwrite the previous value for that key, so only the last value for that key remains, as dictionaries cannot have duplicate keys.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the dictionary state after step 2?
A{1: 1, 2: 4}
B{2: 4}
C{1: 1, 3: 9}
D{}
💡 Hint
Check the 'Dictionary state' column at step 2 in the execution_table.
At which step does the variable x have the value 3?
AStep 1
BStep 2
CStep 3
DEnd
💡 Hint
Look at the 'x (current item)' column in the execution_table.
If the list numbers was empty, what would the final dictionary be?
A{None: None}
B{}
CError
D{0: 0}
💡 Hint
An empty iterable means no items to process, so the dictionary stays empty.
Concept Snapshot
Dictionary comprehension syntax:
{key_expression: value_expression for item in iterable}
Creates a new dictionary by looping over iterable.
Each item produces one key:value pair.
Keys must be unique; later duplicates overwrite earlier.
Use curly braces { } to create dictionary comprehension.
Full Transcript
This visual execution shows how basic dictionary comprehension works in Python. We start with a list of numbers. For each number x, we create a key:value pair where the key is x and the value is x squared. Step by step, the dictionary grows by adding these pairs. After processing all items, the final dictionary contains each number and its square. The variable tracker shows how x changes each step and how the dictionary builds up. Key moments clarify why the dictionary updates each step and what happens with duplicate keys. The quiz tests understanding of dictionary state at different steps and behavior with empty input.