Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python Dictionary: Iteration (Looping)

Python Dictionary Iteration - Complete Guide

Learn how to iterate over dictionaries using for loops, items(), keys(), and values().

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Introduction to Dictionary Iteration
  • Iterating Over Keys
  • Iterating Over Values
  • Iterating Over Key-Value Pairs
  • Ordered Iteration
  • Filtering During Iteration
  • Modifying Dictionaries During Iteration
  • Common Mistakes
  • Interactive Editor
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You Will Learn
  • Iterating over keys — using keys() and direct iteration
  • Iterating over values — using values() method
  • Iterating over key-value pairs — using items() method
  • Ordered iteration — sorting and ordered iteration
  • Filtering — filtering during iteration
  • Modifying dictionaries — safe modification during iteration
  • Common mistakes — and how to avoid them

Introduction to Dictionary Iteration

Iteration is the process of accessing each element in a collection sequentially. In Python, dictionaries are iterable objects, but the iteration behavior is different from lists and tuples. Since dictionaries store key-value pairs, you can iterate over keys, values, or both.

The key characteristics of dictionary iteration are:

  • Keys iteration — iterating over keys using keys() or directly
  • Values iteration — iterating over values using values()
  • Items iteration — iterating over key-value pairs using items()
  • Order preservation — Python 3.7+ preserves insertion order

💡 Key concept: Dictionaries are optimized for key lookups, not for iteration. However, iteration over dictionaries is still efficient and commonly used.

Iterating Over Keys

1

Accessing All Keys

You can iterate over dictionary keys using the keys() method or by iterating directly over the dictionary.

# Direct iteration (iterates over keys)
person = {"name": "Alice", "age": 25, "city": "NYC"}
for key in person:
    print(f"Key: {key}")

# Output:
# Key: name
# Key: age
# Key: city

# Using keys() method (explicit)
for key in person.keys():
    print(f"Key: {key}")

# Converting keys to a list
keys_list = list(person.keys())
print(keys_list)  # ['name', 'age', 'city']

# Iterating and accessing values
for key in person:
    print(f"{key}: {person[key]}")

# Checking keys during iteration
for key in person:
    if key == "age":
        print(f"Found age key with value: {person[key]}")

Characteristics:

  • Direct iteration over a dictionary iterates over keys
  • keys() method is explicit and readable
  • Order is preserved (Python 3.7+)
  • Useful for checking key existence

Quick Check: What does direct iteration over a dictionary return? (Answer: Keys)

Iterating Over Values

2

Accessing All Values

The values() method provides a view of all values in the dictionary, which can be iterated over.

# Iterating over values
person = {"name": "Alice", "age": 25, "city": "NYC"}
for value in person.values():
    print(f"Value: {value}")

# Output:
# Value: Alice
# Value: 25
# Value: NYC

# Converting values to a list
values_list = list(person.values())
print(values_list)  # ['Alice', 25, 'NYC']

# Calculating sum of numeric values
scores = {"math": 85, "science": 92, "english": 78}
total = sum(scores.values())
print(f"Total score: {total}")  # 255

# Finding maximum value
max_score = max(scores.values())
print(f"Highest score: {max_score}")  # 92

# Filtering values
for score in scores.values():
    if score >= 80:
        print(f"Good score: {score}")

Characteristics:

  • values() returns a view of all values
  • Order is preserved (Python 3.7+)
  • Can contain duplicate values
  • Useful for performing operations on values

Quick Check: Can values() contain duplicate values? (Answer: Yes, because values are not required to be unique)

Iterating Over Key-Value Pairs

3

Accessing Both Keys and Values

The items() method is the most commonly used method for iterating over dictionaries. It returns key-value pairs as tuples.

# Iterating over items
person = {"name": "Alice", "age": 25, "city": "NYC"}
for key, value in person.items():
    print(f"{key}: {value}")

# Output:
# name: Alice
# age: 25
# city: NYC

# Using items() in comprehensions
scores = {"math": 85, "science": 92, "english": 78}
passed = {subject: score for subject, score in scores.items() if score >= 80}
print(passed)  # {'math': 85, 'science': 92}

# Iterating and modifying values
for key, value in scores.items():
    print(f"{key}: {value + 5}")  # Adding 5 to each score

# Unpacking items
for subject, score in scores.items():
    if score >= 90:
        print(f"{subject}: Excellent!")

# Using items() with enumerate
for i, (key, value) in enumerate(scores.items()):
    print(f"{i+1}. {key}: {value}")

Characteristics:

  • items() returns a view of (key, value) tuples
  • Most common and Pythonic way to iterate
  • Allows unpacking in the loop
  • Order is preserved (Python 3.7+)

Quick Check: What does items() return when iterated? (Answer: (key, value) tuples)

Ordered Iteration

4

Iterating in a Specific Order

In Python 3.7+, dictionaries preserve insertion order. You can also use sorted() to iterate in a custom order.

# Insertion order is preserved
person = {"name": "Alice", "age": 25, "city": "NYC"}
for key in person:
    print(key)  # name, age, city

# Iterating in sorted order (by keys)
scores = {"math": 85, "science": 92, "english": 78}
for subject in sorted(scores.keys()):
    print(f"{subject}: {scores[subject]}")
# english: 78
# math: 85
# science: 92

# Iterating in reverse order
for key in reversed(list(person.keys())):
    print(f"{key}: {person[key]}")
# city: NYC
# age: 25
# name: Alice

# Sorting by values
scores = {"math": 85, "science": 92, "english": 78}
for subject, score in sorted(scores.items(), key=lambda item: item[1]):
    print(f"{subject}: {score}")
# english: 78
# math: 85
# science: 92

# Sorting by values (descending)
for subject, score in sorted(scores.items(), key=lambda item: item[1], reverse=True):
    print(f"{subject}: {score}")
# science: 92
# math: 85
# english: 78

Characteristics:

  • Python 3.7+ preserves insertion order
  • Use sorted() for custom ordering
  • Use reversed() for reverse order
  • Sorting by values requires items() and key parameter

Quick Check: Does Python 3.7+ preserve dictionary order? (Answer: Yes — insertion order is preserved)

Filtering During Iteration

5

Iterating with Conditions

You can filter dictionary items during iteration using conditional statements or comprehensions.

# Using if statements
scores = {"math": 85, "science": 92, "english": 78}
for subject, score in scores.items():
    if score >= 80:
        print(f"Passing: {subject} - {score}")

# Using dictionary comprehension
passed = {subject: score for subject, score in scores.items() if score >= 80}
print(passed)  # {'math': 85, 'science': 92}

# Filtering keys
person = {"name": "Alice", "age": 25, "city": "NYC", "email": "alice@example.com"}
for key in person:
    if key.startswith('a'):
        print(f"{key}: {person[key]}")

# Filtering values
for key, value in person.items():
    if isinstance(value, str):
        print(f"String: {key} -> {value}")

# Complex filtering
for subject, score in scores.items():
    if score >= 85 and subject.startswith('s'):
        print(f"{subject}: {score}")

Methods:

  • Conditional statements — iterate with if conditions
  • Dictionary comprehension — create filtered dictionaries
  • Key filtering — filter by key properties
  • Value filtering — filter by value properties

Modifying Dictionaries During Iteration

6

Safe Modification Techniques

Modifying a dictionary during iteration can cause errors. Here are safe ways to do it.

# WRONG — modifies during iteration (raises RuntimeError)
scores = {"math": 85, "science": 92, "english": 78}
# for subject in scores:
#     if scores[subject] < 80:
#         del scores[subject]  # RuntimeError: dictionary changed size during iteration

# CORRECT — iterate over a copy of keys
scores = {"math": 85, "science": 92, "english": 78}
for subject in list(scores.keys()):
    if scores[subject] < 80:
        del scores[subject]
print(scores)  # {'math': 85, 'science': 92}

# CORRECT — create a new dictionary
scores = {"math": 85, "science": 92, "english": 78}
filtered = {k: v for k, v in scores.items() if v >= 80}
print(filtered)  # {'math': 85, 'science': 92}

# CORRECT — using a list of keys to remove
to_remove = [subject for subject, score in scores.items() if score < 80]
for subject in to_remove:
    del scores[subject]
print(scores)  # {'math': 85, 'science': 92}

# Updating values during iteration (safe)
scores = {"math": 85, "science": 92, "english": 78}
for subject in scores:
    scores[subject] += 5  # Safe — updating values doesn't change size
print(scores)  # {'math': 90, 'science': 97, 'english': 83}

Guidelines:

  • Iterate over a copy — list(dict.keys())
  • Use comprehension — create a new dictionary
  • Collect keys to remove — then remove after iteration
  • Updating values — safe during iteration

Quick Check: What happens if you modify a dictionary during iteration? (Answer: RuntimeError: dictionary changed size during iteration)

Common Mistakes

7

Watch Out For These!

Mistake 1: Modifying Dictionary During Iteration

# WRONG — raises RuntimeError
scores = {"math": 85, "science": 92, "english": 78}
# for subject in scores:
#     if scores[subject] < 80:
#         del scores[subject]  # RuntimeError

# CORRECT — iterate over a copy
for subject in list(scores.keys()):
    if scores[subject] < 80:
        del scores[subject]

Mistake 2: Forgetting .items() When Unpacking

# WRONG — iterating over keys only
person = {"name": "Alice", "age": 25}
# for key, value in person:  # ValueError: too many values to unpack

# CORRECT — use items()
for key, value in person.items():
    print(f"{key}: {value}")

Mistake 3: Assuming Order in Older Python Versions

# WRONG — order is not guaranteed in Python 3.6 and earlier
my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict:
    print(key)  # Order may vary

# CORRECT — use OrderedDict if order is critical
from collections import OrderedDict
ordered = OrderedDict([("a", 1), ("b", 2), ("c", 3)])
for key in ordered:
    print(key)  # a, b, c

Quick Check: What is the most common mistake when iterating over dictionaries? (Answer: Modifying the dictionary during iteration)

Interactive Editor

Experiment with dictionary iteration techniques directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
DICTIONARY ITERATION PRACTICE
========================================

Person: {'name': 'Alice', 'age': 25, 'city': 'NYC', 'email': 'alice@example.com'}
Scores: {'math': 85, 'science': 92, 'english': 78}

1. ITERATING OVER KEYS
Key: name
Key: age
Key: city
Key: email

2. ITERATING OVER VALUES
Value: Alice
Value: 25
Value: NYC
Value: alice@example.com

3. ITERATING OVER ITEMS
name: Alice
age: 25
city: NYC
email: alice@example.com

4. ORDERED ITERATION
english: 78
math: 85
science: 92

5. FILTERING
Passing: math - 85
Passing: science - 92

6. DICTIONARY COMPREHENSION
Filtered scores: {'math': 85, 'science': 92}

Dictionary iteration practice complete!
🏆

Certificate of Completion

You have completed the Python Dictionary Iteration tutorial. You understand iterating over keys, values, items, ordered iteration, filtering, and modifying dictionaries during iteration.

Quick Quiz — Test Your Knowledge

Let's see what you've learned about dictionary iteration:

1. What does direct iteration over a dictionary return?
2. Which method returns key-value pairs for iteration?
3. Does Python 3.7+ preserve dictionary insertion order?
4. What happens if you modify a dictionary during iteration?
5. How do you safely remove items from a dictionary during iteration?

Frequently Asked Questions

What is the most Pythonic way to iterate over a dictionary? ▼

The most Pythonic way is to use for key, value in dict.items(): when you need both keys and values. Use for key in dict: when you only need keys.

Can I modify a dictionary while iterating over it? ▼

You cannot modify the size of a dictionary during iteration (adding or removing keys). Updating existing values is safe. To remove items, iterate over a copy of the keys: for key in list(dict.keys()):.

Does dictionary iteration preserve order? ▼

Yes, in Python 3.7 and later, dictionaries preserve insertion order. In earlier versions, order was not guaranteed. Use OrderedDict if order is critical.

How do I iterate over a dictionary in sorted order? ▼

Use sorted(): for key in sorted(dict.keys()): for keys, or for key, value in sorted(dict.items()): for both keys and values.

What is the difference between keys(), values(), and items()? ▼

keys() returns only keys, values() returns only values, and items() returns key-value pairs as tuples. All return view objects that reflect changes to the dictionary.

How do I filter a dictionary during iteration? ▼

Use dictionary comprehension: {k: v for k, v in dict.items() if condition}, or use a loop with an if statement and collect items to keep.

Where to Go From Here

After mastering dictionary iteration, consider exploring these related topics:

Formatting Dictionaries

Learn how to format and display dictionaries effectively.

Learn More →

Nested Dictionaries

Work with dictionaries within dictionaries.

Learn More →

Dictionary Comprehension

Create dictionaries concisely using comprehension syntax.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Top PL SQL Interview Questions
Previous: Dictionary Methods Next: Formatting Dictionaries →