0
0
Pythonprogramming~10 mins

Dictionary iteration in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Dictionary iteration
Start with dictionary
Pick one key-value pair
Use key and/or value
More pairs?
YesPick next pair
No
End
We start with a dictionary, pick each key-value pair one by one, use them, and repeat until all pairs are processed.
Execution Sample
Python
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
    print(key, value)
This code goes through each key and value in the dictionary and prints them.
Execution Table
StepCurrent PairKeyValueActionOutput
1('a', 1)a1Print key and valuea 1
2('b', 2)b2Print key and valueb 2
3('c', 3)c3Print key and valuec 3
4No more pairs--Loop ends-
💡 All key-value pairs have been processed, loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
key-abc-
value-123-
Key Moments - 2 Insights
Why do we use .items() to get both key and value?
Using .items() returns pairs of key and value together, so in each loop step we get both. Without .items(), looping over the dictionary gives only keys (see execution_table rows 1-3).
What happens if the dictionary is empty?
The loop body does not run at all because there are no pairs to pick. The loop ends immediately (like step 4 in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'key' at step 2?
Ab
Ba
Cc
D-
💡 Hint
Check the 'key' column in variable_tracker after step 2.
At which step does the loop stop running?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Look at the exit_note and the last row in execution_table.
If we looped over my_dict without .items(), what would the loop variable hold?
AValues only
BKeys only
CKey-value pairs
DNothing
💡 Hint
Recall the key_moments explanation about .items() and dictionary iteration.
Concept Snapshot
Dictionary iteration:
Use for key, value in dict.items():
  to get each key and its value.
Without .items(), loop gives keys only.
Loop runs once per key-value pair.
Stops when all pairs are done.
Full Transcript
Dictionary iteration means going through each key and value in a dictionary one by one. We use a for loop with .items() to get both key and value together. In each step, the loop picks one pair, lets us use the key and value, then moves to the next. When no pairs remain, the loop ends. If the dictionary is empty, the loop does not run. Without .items(), looping over a dictionary gives only keys, not values. This is important to remember when you want both parts. The example code prints each key and value. The execution table shows each step clearly, with the current pair, key, value, and output. The variable tracker shows how key and value change each step. This helps beginners see exactly what happens inside the loop.