For Loop with Dictionaries

2 min read ·

A dictionary stores data in key–value pairs. A for loop is used to iterate through keys, values, or both.

Basic Syntax

  • By default, for loop iterates over keys

Simple Example (Keys Only)


Accessing Values Using Keys


Loop Through Values Only


Loop Through Keys and Values


Dictionary with Conditional Logic


Loop Through Nested Dictionary


Common Mistake

Caution

To get both key and value, always use .items().


Exercise