Python Iterate Dict: Complete Guide

Mateen Kiani

Mateen Kiani

Published on Tue Jul 22 2025·4 min read

python-iterate-dict:-complete-guide

Basic Key Loop

When you first start working with Python, looping through a dictionary by its keys feels natural and straightforward. You simply write a for loop that addresses each key one after another. This method is clear and concise, making it ideal for many everyday tasks.

Consider the following example:

user_ages = {'Alice': 30, 'Bob': 25, 'Carol': 27}
for name in user_ages:
print(f"{name} is {user_ages[name]} years old.")

Here, for name in user_ages iterates over the keys by default. Inside the loop, you access the value with user_ages[name]. This approach works well for simple lookups and scenarios where you only need the key or both key and value.

Practical Tip: If you prefer to make it explicit, you can call user_ages.keys(), but it behaves identically:

for name in user_ages.keys():
print(name)

Using the basic key loop is a good starting point. However, as you deal with larger or more complex structures, you might look for ways to access values directly or even unpack both parts at once. Let’s explore those options next.

Values and Items

Sometimes you only need to work with the values in a dictionary. Python offers the values() method to iterate directly over those values without touching the keys.

prices = {'apple': 0.40, 'banana': 0.25, 'cherry': 0.15}
for price in prices.values():
total += price

On the other hand, when you need both keys and values together, items() is your most powerful ally:

for fruit, cost in prices.items():
print(f"A {fruit} costs ${cost}")

This unpacking pattern makes your code more readable and reduces extra lookups.

Key Differences:

  • keys(): Iterates over keys only.
  • values(): Iterates over values only.
  • items(): Iterates over (key, value) pairs.

Practical Tip: If you need to modify the dictionary while iterating, loop over a list copy:

for key in list(prices):
if prices[key] < 0.2:
del prices[key]

This avoids runtime errors and unexpected behavior.

Nested Structures

Real-world data often uses nested dictionaries. You might have a master record where each key points to another dictionary of details.

users = {
'alice': {'age': 30, 'city': 'NY'},
'bob': {'age': 25, 'city': 'LA'}
}

To extract every inner field, you can nest loops:

for user, info in users.items():
for field, value in info.items():
print(f"{user}.{field} = {value}")

This double iteration handles any depth if you generalize it with recursion. For very deep or variable nesting, a helper function can streamline the process:

def recurse_dict(dct, parent_key=''):
for k, v in dct.items():
path = f"{parent_key}.{k}" if parent_key else k
if isinstance(v, dict):
yield from recurse_dict(v, path)
else:
yield path, v
for key_path, val in recurse_dict(users):
print(f"{key_path}: {val}")

This yields a flat view of every terminal value with its full path. It’s a handy trick when you need to export or analyze nested data.

Comprehensions

Python comprehensions let you build new collections in a single expression. For dictionaries, you can filter, transform, and rebuild with elegant syntax:

# Swap keys and values
dict_swap = {val: key for key, val in prices.items()}
# Filter entries
cheap_fruits = {k: v for k, v in prices.items() if v < 0.3}

Comprehensions are not only shorter but often faster than regular loops.

Practical Tip: Use dict comprehensions when the transformation is straightforward. For complex logic, stick with a standard loop.

Examples:

  • Convert string keys to uppercase:

    upper_keys = {k.upper(): v for k, v in prices.items()}
  • Combine two lists into a dict:

    names = ['a','b','c']
    vals = [1,2,3]
    zipped = {n: v for n, v in zip(names, vals)}

Comprehensions keep your code concise and idiomatic.

JSON File Operations

When working with APIs or configuration files, you often load or save dictionaries as JSON. Python’s built-in json module makes this straightforward.

Reading a JSON file:

import json
with open('data.json') as f:
data = json.load(f)
for key, val in data.items():
print(key, val)

Writing a dictionary back to disk:

with open('output.json', 'w') as f:
json.dump(data, f, indent=2)

If you need deeper control or want to parse strings, see this Python JSON parser guide. And for advanced file operations, check out how to write JSON files with custom settings.

Practical Tip: Always handle errors and use try/except when loading external files.

Conclusion

Iterating over Python dictionaries is a core skill that scales from simple key loops to handling nested data and file operations. You’ve seen how to loop keys, values, and item pairs. You learned about nested loops and recursive helpers, and you discovered the power of dict comprehensions. Finally, you explored how to read from and write to JSON files while linking to specialized resources.

With these patterns in your toolkit, you’ll write cleaner, faster, and more robust code. Whether you’re analyzing API responses, transforming data, or building configuration tools, understanding these iteration methods empowers you to handle dictionaries of any shape. Dive in, experiment with each approach, and soon iterating dicts will become second nature.


Mateen Kiani
Mateen Kiani
kiani.mateen012@gmail.com
I am a passionate Full stack developer with around 3 years of experience in MERN stack development and 1 year experience in blockchain application development. I have completed several projects in MERN stack, Nextjs and blockchain, including some NFT marketplaces. I have vast experience in Node js, Express, React and Redux.