Looping Through Dicts

In Python, dict (dictionary) is one of the most powerful and commonly used data structures. It stores data in key-value pairs, allowing you to quickly access values by their associated keys. But what if you want to perform an operation on every item within a dictionary? That’s where looping through dicts becomes essential. This lesson will guide you through the various ways to iterate over dictionaries effectively and idiomatically.

By the end, you will confidently navigate the keys, values, and items within dictionaries, enabling you to manipulate data structures like a pro.

Understanding the Anatomy of a Dictionary

Before diving into looping, let's briefly recall the structure of a dictionary:

  • Key: A unique identifier for each value; must be immutable (e.g., strings, numbers, tuples).
  • Value: Data associated with a key; can be any Python object.

Example dictionary:

📌 Deep Dive: Simple Dictionary

PYTHON
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

Here, name, age, and city are keys; "Alice", 30, and "New York" are their respective values.

Looping Over Dictionary Keys

By default, when you iterate over a dictionary, you are iterating over its keys.

📌 Deep Dive: Looping Through Keys

PYTHON
for key in person:
    print(key)
Output
name age city

Alternatively, you can be explicit using the .keys() method:

📌 Deep Dive: Using .keys()

PYTHON
for key in person.keys():
    print(key)
Output
name age city

When to use: Use this form if you want to emphasize you’re iterating over keys or when working with dictionary views explicitly.

Looping Over Dictionary Values

Sometimes you are only interested in the values stored in a dictionary. Python provides the .values() method to loop through these values directly.

📌 Deep Dive: Looping Through Values

PYTHON
for value in person.values():
    print(value)
Output
Alice 30 New York

This method is useful when the keys are irrelevant to your task, and you want to process or analyze the values only.

Looping Over Key-Value Pairs with .items()

Most often, you'll want access to both keys and their associated values simultaneously. The .items() method returns an iterable of key-value pairs as tuples, allowing you to unpack them directly in your for loop.

📌 Deep Dive: Looping Through Items

PYTHON
for key, value in person.items():
    print(f"{key}: {value}")
Output
name: Alice age: 30 city: New York

This pattern is the most common and idiomatic way to process dictionaries when keys and values are both needed.

Comparing the Looping Methods

Dictionary Looping Methods Comparison
MethodYieldsUse Case
for key in dictKeysSimple key iteration, concise
for key in dict.keys()KeysExplicit key iteration
for value in dict.values()ValuesWhen only values matter
for key, value in dict.items()Key-value pairsMost common for full access

Looping Through Nested Dictionaries

Dictionaries can contain other dictionaries as values, forming nested structures. Looping through such nested dictionaries requires nested loops to access inner keys and values.

Consider this example:

📌 Deep Dive: Nested Dictionary Looping

PYTHON
users = {
    "alice": {"age": 30, "city": "New York"},
    "bob": {"age": 25, "city": "Paris"},
    "charlie": {"age": 35, "city": "London"}
}

for user, info in users.items():
    print(f"User: {user}")
    for key, value in info.items():
        print(f"  {key}: {value}")
Output
User: alice age: 30 city: New York User: bob age: 25 city: Paris User: charlie age: 35 city: London

This approach lets you drill into complex dictionary structures comfortably.

Modifying a Dictionary While Looping

Modifying a dictionary (adding or removing keys) while looping over it can cause unexpected behavior or runtime errors. To avoid problems, iterate over a copy of the dictionary keys or items.

⚠️ Caution When Modifying Dictionaries During Loops

Directly changing the size of a dictionary while iterating over it causes a RuntimeError. Always loop over a list copy of keys or items if modification is needed.

📌 Deep Dive: Safe Modification During Loop

PYTHON
# Unsafe approach (may cause error)
# for key in person:
#     if key == "age":
#         del person[key]

# Safe approach:
for key in list(person.keys()):
    if key == "age":
        del person[key]

print(person)
Output
{'name': 'Alice', 'city': 'New York'}

Here, list(person.keys()) creates a static list copy of keys, allowing us to safely delete items from the original dictionary.

Using Dictionary Comprehensions with Loops

Looping through dictionaries isn’t just for printing or accessing data. You can also use loops within dictionary comprehensions to create new dictionaries efficiently.

📌 Deep Dive: Dictionary Comprehension Example

PYTHON
# Create a new dict with ages doubled
doubled_ages = {key: value * 2 for key, value in person.items() if isinstance(value, int)}
print(doubled_ages)
Output
{'age': 60}

Here, the comprehension loops through person.items(), selects only integer values, and doubles them.

Looping Through Dictionaries Using enumerate()

Sometimes, you might want the current iteration count alongside keys or values. Using enumerate() lets you do this conveniently.

📌 Deep Dive: Using enumerate() with Dictionaries

PYTHON
for index, key in enumerate(person):
    print(f"{index}: {key} -> {person[key]}")
Output
0: name -> Alice 1: age -> 30 2: city -> New York

Use this when the position of the key-value pair matters, such as in ordered operations or debugging.

Looping Through Dictionaries in Python 3.7+ and Order Preservation

Since Python 3.7, dictionaries preserve the insertion order of keys. This means looping through a dictionary will follow the order in which keys were added.

This behavior enables predictable iteration order without needing to use specialized ordered dict types.

💡 Order Preservation in Python Dictionaries

From Python 3.7 onwards, the standard dict type keeps keys in insertion order by default. This makes loops over dictionaries deterministic and reliable.

Summary: Best Practices for Looping Through Dicts

  • for key in dict or for key in dict.keys() — iterate over keys.
  • for value in dict.values() — iterate over values only.
  • for key, value in dict.items() — iterate over key-value pairs simultaneously; most common usage.
  • Use list(dict.keys()) when modifying dict inside the loop.
  • Utilize dictionary comprehensions to create new dicts based on looping logic.
  • Remember, starting Python 3.7, dicts maintain insertion order.
Architecture of Looping Through Dicts
Architecture of Looping Through Dicts

Mastering these looping techniques is crucial for effective Python programming, especially when handling complex data structures or working with APIs, configurations, and data transformations.