How to Iterate Through a Dictionary in Python (Keys, Values, & Items)
Learn how to loop or iterate through a Python dictionary. Discover methods to loop over keys, values, and key-value pairs with clean, runnable examples.
Explanation
Iterating over dictionaries is a fundamental task in Python programming, as dictionaries are widely used to store key-value data such as database records, API payloads, and configuration settings. Python provides several intuitive, built-in methods to traverse dictionaries depending on whether you need the keys, the values, or both. Understanding these methods is crucial for writing clean, efficient, and readable code.
The most common way to iterate through both keys and values simultaneously is by using the `.items()` method. This method returns a view object containing tuples of key-value pairs, which can be easily unpacked directly inside a `for` loop statement. This is generally preferred over iterating through keys and looking up values manually, as it is both more readable and more efficient.
If you only need keys, you can loop directly over the dictionary itself or use the `.keys()` method explicitly. To iterate only over the values, Python provides the `.values()` method. Both of these view objects are dynamic, reflecting any changes made to the dictionary, and support membership testing using the `in` operator.
Step-by-Step Implementation
- 1
Use user.items() in a for loop to extract and unpack both keys and values simultaneously.
- 2
Loop directly over the dictionary (or call .keys()) to iterate through the keys only.
- 3
Use .values() to isolate and iterate through the values of the dictionary.
Code Example
This code demonstrates iterating over a dictionary keys, values, and key-value pairs.
user = {"username": "alice", "role": "admin", "active": "True"}
# 1. Iterate over keys and values using items()
print("--- Keys and Values ---")
for key, value in user.items():
print(f"{key}: {value}")
# 2. Iterate over keys only (default behavior)
print("\n--- Keys Only ---")
for key in user:
print("Key:", key)
# 3. Iterate over values only
print("\n--- Values Only ---")
for val in user.values():
print("Value:", val)--- Keys and Values ---
username: alice
role: admin
active: True
--- Keys Only ---
Key: username
Key: role
Key: active
--- Values Only ---
Value: alice
Value: admin
Value: TrueFrequently Asked Questions
Is the order of insertion preserved when iterating over a dictionary?
Yes, starting in Python 3.7+, dictionaries are guaranteed to maintain the insertion order of keys.
Can you modify a dictionary while iterating over it?
No, modifying keys (adding or deleting) during iteration will raise a RuntimeError. Modify a copy of keys or values instead.
Related How-To Guides
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
Python Dictionary Methods
Learn Python dictionary methods. Complete reference guide for key-value pair insertions, retrievals, updates, and checks.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.