DevAcademia
C++C#CPythonJava
  • Python Fundamentals

  • Introduction to Python
  • Getting Started with Python
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If...Else
  • Python Match
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python OOP

  • Python OOP
  • Python Constructors
  • Python Destructors
  • Python Classes/Objects
  • Python Inheritance
  • Python Polymorphism
  • Python Quiz

  • Python Fundamentals Quiz
  • Python Fundamentals

  • Introduction to Python
  • Getting Started with Python
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If...Else
  • Python Match
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python OOP

  • Python OOP
  • Python Constructors
  • Python Destructors
  • Python Classes/Objects
  • Python Inheritance
  • Python Polymorphism
  • Python Quiz

  • Python Fundamentals Quiz

Loading Python tutorial…

Loading content
Python FundamentalsTopic 59 of 77
←PreviousPrevNextNext→

Loop Dictionaries

Looping Through Dictionaries

A dictionary can be looped through in different ways. By default, iterating over a dictionary loops through its keys. You can also explicitly loop over keys, values, or key-value pairs.

Example
# Looping through a dictionary
person = {"name": "John", "age": 30, "city": "New York"}

# Loop through keys (default)
print("Keys:")
for key in person:
    print(f"- {key}")

# Loop through keys explicitly
print("\nKeys (explicit):")
for key in person.keys():
    print(f"- {key}: {person[key]}")

# Loop through values
print("\nValues:")
for value in person.values():
    print(f"- {value}")

# Loop through key-value pairs
print("\nItems:")
for key, value in person.items():
    print(f"- {key}: {value}")
Output
Keys:
- name
- age
- city

Keys (explicit):
- name: John
- age: 30
- city: New York

Values:
- John
- 30
- New York

Items:
- name: John
- age: 30
- city: New York

Dictionary Comprehensions

Dictionary comprehensions provide a concise way to build or transform dictionaries. They follow the pattern `{key: value for ...}` and can include conditions for filtering.

Example
# Dictionary comprehensions
numbers = [1, 2, 3, 4, 5]

# Create dictionary with squares
squares = {x: x**2 for x in numbers}
print("Squares:", squares)

# Filter dictionary by key length
person = {"name": "John", "age": 30, "city": "New York", "country": "USA"}
filtered = {k: v for k, v in person.items() if len(k) > 3}
print("Filtered:", filtered)

# Transform string values to uppercase
transformed = {k: v.upper() if isinstance(v, str) else v for k, v in person.items()}
print("Transformed:", transformed)
Output
Squares: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Filtered: {'name': 'John', 'city': 'New York', 'country': 'USA'}
Transformed: {'name': 'JOHN', 'age': 30, 'city': 'NEW YORK', 'country': 'USA'}

Nested Loops with Dictionaries

Dictionaries can hold nested structures such as other dictionaries or lists. You can use nested loops to access and process these values.

Example
# Nested loops with dictionaries
students = {
    "John": {"age": 20, "grades": [85, 90, 78]},
    "Jane": {"age": 21, "grades": [92, 88, 95]},
    "Bob": {"age": 19, "grades": [76, 82, 80]}
}

# Calculate average grade for each student
for name, info in students.items():
    avg_grade = sum(info["grades"]) / len(info["grades"])
    print(f"{name}: Age {info['age']}, Average Grade: {avg_grade:.1f}")
Output
John: Age 20, Average Grade: 84.3
Jane: Age 21, Average Grade: 91.7
Bob: Age 19, Average Grade: 79.3
Test your knowledge: Loop Dictionaries
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Python FundamentalsTopic 59 of 77
←PreviousPrevNextNext→