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.
- Understanding their iteration behavior helps you read and write Python code correctly.
- It also helps you choose the right method when you want keys, values, or both.
Python dictionaries provide three common iteration styles:
for k in d:→ keysfor v in d.values():→ valuesfor k, v in d.items():→ key-value pairs
Knowing the difference makes your code clearer and avoids bugs.
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 3
Example: prove that key is just a variable name
d = {'x': 1, 'y': 2, 'z': 3}
for banana in d:
print(banana, d[banana])
This works exactly the same. banana is a strange name, but it is still just a normal variable.
Better alternatives when you want values or pairs
Values only
for value in d.values():
print(value)
Keys and values together
for key, value in d.items():
print(key, 'corresponds to', value)
Using items() is often cleaner than looping over keys and then doing d[key].
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'd[key]meansd['x']d['x']is1- output becomes:
x 1 -
Python asks the iterator for the next key.
-
The iterator returns
'y'. -
Python assigns
'y'tokey. -
The loop body runs again:
keyis'y'd[key]meansd['y']d['y']is2- output becomes:
y 2 -
There are no more keys, so the loop ends.
Important detail: the loop variable key is reassigned on each iteration. It is not built into Python and it is not special.
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')
Building reports from grouped data
sales = {'Monday': 120, 'Tuesday': 150, 'Wednesday': 130}
for day, total in sales.items():
print(f'{day}: ${total}')
In all of these examples, developers choose between keys, values, or items depending on what information is needed.
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
d = {'a': 1, 'b': 2, 'c': 3}
filtered = {k: v for k, v in d.items() if v > 1}
This pattern is widely used for transforming dictionaries.
5. Use .get() when a key might be missing
If you are iterating over one collection and looking up values in another dictionary, .get() helps avoid errors:
prices = {'apple': 2, 'banana': 1}
items = ['apple', 'orange']
for item in items:
print(prices.get(item, 0))
In real code, readability matters a lot. Even though for banana in d: works, developers prefer clear names like key, name, field, or user_id.
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:
d = {'x': 1, 'y': 2}
for key, value in d:
print(key, value)
Why it fails:
- iterating over
dreturns one key at a time - each key is a string like
'x' - Python cannot unpack that into
key, valuethe way you intend
Fix:
for key, value in d.items():
print(key, value)
Mistake 4: changing dictionary size during iteration
Broken code:
d = {'a': 1, 'b': 2}
for key in d:
del d[key]
This can raise an error because the dictionary changes while Python is iterating over it.
Safer approach:
for key in list(d.keys()):
del d[key]
Mistake 5: using d[key] when items() is simpler
Less clear:
for key in d:
print(key, d[key])
Cleaner:
for key, value in d.items():
print(key, value)
Both are valid, but items() is often easier to read when you need both parts.
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(): |
for key in d vs for key in d.keys()
These usually behave the same for normal iteration.
for key in d:
print(key)
for key in d.keys():
print(key)
Many Python developers prefer for key in d: because it is shorter and idiomatic.
d[key] lookup vs items()
| Approach | Example | Notes |
|---|---|---|
| Key loop + lookup | for key in d: print(key, d[key]) | Fine, but does an extra lookup |
items() | for key, value in d.items(): print(key, value) | Cleaner when both are needed |
Variable name vs keyword
| Name | Is it special? | Can you change it? |
|---|---|---|
key | No | Yes |
k | No | Yes |
banana | No | Yes |
The special behavior comes from the dictionary object, not from the variable name.
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 in d:
print(k) # a, b
for v in d.values():
print(v) # 10, 20
for k, v in d.items():
print(k, v) # a 10, b 20
Edge case
This is wrong if you expect pairs:
for k, v in d:
pass
Use this instead:
for k, v in d.items():
pass
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, name, or field.
Why does for key, value in d fail?
Because iterating over d gives one key at a time, not a (key, value) pair. Use d.items() if you want both.
Should I use d[key] or items()?
If you need both the key and the value, items() is usually clearer and more idiomatic.
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.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.