Question
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
In this Python code, the loop iterates over a dictionary and prints each key along with its corresponding value.
How does Python know to iterate over only the keys of the dictionary in a for loop? Is key a special Python keyword, or is it just a normal variable name?
Short Answer
By the end of this page, you will understand how Python iterates over dictionaries in a for loop, why looping over a dictionary gives you keys by default, and why names like key are just regular variables. You will also see how to iterate over keys, values, and key-value pairs in real Python code.
Concept
In Python, a for loop does not look for a special variable name like key. Instead, it asks the object on the right side of in how it should be iterated.
When you write:
for key in d:
...
Python asks the dictionary d for an iterator. A dictionary's default iterator produces its keys. That is why the loop variable receives one key at a time.
So in this example:
dis a dictionaryfor ... in dmeans "iterate overd"- dictionaries iterate over keys by default
keyis just a variable name chosen by the programmer
You could write the same loop like this:
for anything_you_want in d:
print(anything_you_want, d[anything_you_want])
This works the same way, although key is much more readable.
Why this matters:
- Dictionaries are one of Python's most common data structures.
Mental Model
Think of a dictionary like a labeled cabinet:
- the label on each drawer is the key
- the contents inside the drawer are the value
When Python loops over a dictionary directly, it walks past the cabinet and reads the drawer labels first. It does not automatically open the drawers.
So:
for key in d:
means:
- "give me each drawer label one at a time"
Then this part:
d[key]
means:
- "now open the drawer with that label and get its contents"
Also, key is not a magic word. It is just the label you wrote on your notepad while walking past the cabinet. You could call it label, k, or name.
Syntax and Examples
The basic syntax is:
for variable in dictionary:
# variable receives each key
Example: iterate over keys
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key)
Output:
x
y
z
Here, key gets each dictionary key one at a time.
Example: access the value from the key
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
Output:
x corresponds to 1
y corresponds to 2
z corresponds to
Step by Step Execution
Consider this code:
d = {'x': 1, 'y': 2}
for key in d:
print(key, d[key])
Step by step:
-
Python creates the dictionary:
{'x': 1, 'y': 2} -
Python reaches:
for key in d: -
Python asks the dictionary for an iterator.
-
The dictionary iterator returns the first key:
'x'. -
Python assigns
'x'to the loop variablekey. -
Python runs the loop body:
print(key, d[key])keyis'x'
Real World Use Cases
Dictionary iteration is used constantly in real Python programs.
Processing configuration settings
config = {'host': 'localhost', 'port': 8000, 'debug': True}
for key, value in config.items():
print(f'{key} = {value}')
Validating API response fields
user = {'id': 10, 'name': 'Ava', 'email': 'ava@example.com'}
for field in user:
print('Checking field:', field)
Counting results
scores = {'math': 90, 'science': 85, 'history': 88}
for subject, score in scores.items():
if score >= 90:
print(subject, 'is excellent')
Real Codebase Usage
In real projects, developers usually pick the most direct dictionary iteration pattern.
1. Use for key in d when only keys matter
for field in payload:
if field not in allowed_fields:
print('Unexpected field:', field)
This is common for validation and filtering.
2. Use items() when both key and value are needed
for name, enabled in feature_flags.items():
if enabled:
print('Enabled:', name)
This is one of the most common patterns in production code.
3. Use guard clauses with dictionary data
for key, value in settings.items():
if value is None:
continue
print(key, value)
This skips invalid or empty values early.
4. Combine with comprehensions
Common Mistakes
Mistake 1: thinking key is a reserved keyword
Broken idea:
for key in d:
print(key)
Some beginners think key has special meaning. It does not.
This also works:
for k in d:
print(k)
Avoid confusion by remembering: the variable name is your choice.
Mistake 2: expecting values when looping over a dictionary directly
Broken expectation:
d = {'x': 1, 'y': 2}
for value in d:
print(value) # prints keys, not values
Fix:
for value in d.values():
print(value)
Mistake 3: unpacking incorrectly
Broken code:
Comparisons
| Pattern | What it iterates over | Best when | Example |
|---|---|---|---|
for key in d: | Keys | You only need keys | for key in d: |
for key in d.keys(): | Keys | You want to be explicit | for key in d.keys(): |
for value in d.values(): | Values | You only need values | for value in d.values(): |
for key, value in d.items(): | Key-value pairs | You need both key and value | for key, value in d.items(): |
Cheat Sheet
# Loop over dictionary keys (default behavior)
for key in d:
print(key)
# Equivalent explicit form
for key in d.keys():
print(key)
# Loop over values
for value in d.values():
print(value)
# Loop over key-value pairs
for key, value in d.items():
print(key, value)
Rules to remember
for x in dictionary:iterates over keys by defaultkeyis not a Python keyword- the loop variable can have any valid name
- use
items()when you need both key and value - use
values()when you need only values - avoid changing dictionary size while iterating over it
Quick examples
d = {'a': 10, 'b': 20}
for k d:
(k)
FAQ
Why does for key in my_dict return keys in Python?
Because a dictionary's default iterator is defined to produce keys. When Python loops over the dictionary itself, it gets keys unless you ask for something else.
Is key a reserved word in Python?
No. key is just a normal variable name chosen by the programmer.
How do I loop over dictionary values instead of keys?
Use:
for value in my_dict.values():
print(value)
How do I loop over both keys and values in a dictionary?
Use:
for key, value in my_dict.items():
print(key, value)
Is for key in d the same as for key in d.keys()?
Yes, for normal iteration they both iterate over keys. for key in d is shorter and very common.
Can I use another variable name instead of key?
Yes. Any valid variable name works, such as k, , or .
Mini Project
Description
Create a small Python script that prints a summary of products stored in a dictionary. This project helps you practice the difference between iterating over keys, values, and key-value pairs. It also reinforces that loop variable names are just ordinary variables.
Goal
Build a script that reads a dictionary of products and prices, then prints each product with its price and a final count of how many products exist.
Requirements
- Create a dictionary with at least three product names as keys and prices as values.
- Use a
forloop to iterate through the dictionary. - Print each product name and its corresponding price.
- Print all prices separately using
.values(). - Print the total number of products at the end.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.