How to Iterate Over a Dictionary in Python?

Advertisement

May 11, 2025 By Tessa Rodriguez

Working with dictionaries is a regular part of writing Python code. They hold key-value pairs and give you the flexibility to store data with labels instead of relying only on indexes. But when it’s time to access or manipulate the data, you’ll need a good grip on how to loop through it properly. Python offers several clean and readable ways to iterate over dictionaries, and depending on what exactly you want to do—whether it’s accessing keys, values, or both—there’s a right method for each use case.

Let’s walk through all the ways you can iterate over a Python dictionary without repeating the logic or dragging it out longer than needed.

How to Iterate Over a Dictionary in Python?

Looping Through Keys

If you just need the keys from the dictionary, this is the simplest way to go. You can loop directly through the dictionary, and Python will give you the keys by default.

python

CopyEdit

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}

for key in my_dict:

print(key)

This is the most common pattern you’ll see. It’s short and does the job well. You can also make it a little more obvious by calling .keys():

python

CopyEdit

for key in my_dict.keys():

print(key)

There’s no difference in output, but it can sometimes help with clarity, especially when someone else is reading your code.

Looping Through Values

Sometimes you don’t care about the keys at all and just want to work with the values. That’s where .values() comes in.

python

CopyEdit

for value in my_dict.values():

print(value)

This returns just the values in the order they appear. There’s no key to go with them, so make sure you don’t need that information.

Looping Through Key-Value Pairs

If you want both keys and values at the same time, use .items(). This is often the most useful way to work with a dictionary.

python

CopyEdit

for key, value in my_dict.items():

print(f"{key}: {value}")

This method is straightforward and keeps your code easy to read. You get full access to each pair in one go, which is handy when you need to process or compare data.

Looping with Index Using enumerate()

If you need the index while looping through a dictionary, combine .items() with enumerate(). This helps when the position of each item matters for what you’re doing.

python

CopyEdit

for index, (key, value) in enumerate(my_dict.items()):

print(f"{index}: {key} = {value}")

The index will count from zero, just like in a regular list loop. It doesn't change the dictionary; it just gives you an ordered way to work through it.

Iterating Over a Sorted Dictionary

Dictionaries keep insertion order in Python 3.7 and above, but if you want to loop through keys in sorted order, use sorted().

python

CopyEdit

for key in sorted(my_dict):

print(f"{key}: {my_dict[key]}")

You can also sort by value:

python

CopyEdit

for key in sorted(my_dict, key=my_dict.get):

print(f"{key}: {my_dict[key]}")

This is useful when you're preparing data for display or want to apply logic based on rank.

Iterating in Reverse

To go through the dictionary in reverse order, use reversed() with sorted() or loop through a reversed list of items.

python

CopyEdit

for key in reversed(list(my_dict)):

print(f"{key}: {my_dict[key]}")

Or with .items():

python

CopyEdit

for key, value in reversed(list(my_dict.items())):

print(f"{key}: {value}")

This doesn’t flip the dictionary itself—it just loops backward through the pairs.

Using Dictionary Comprehension

While this isn't always considered iteration in the traditional sense, it still loops behind the scenes. It's useful for transforming data or filtering a dictionary.

Example: creating a new dictionary with values doubled.

python

CopyEdit

new_dict = {key: value * 2 for key, value in my_dict.items()}

Or filtering:

python

CopyEdit

filtered_dict = {key: value for key, value in my_dict.items() if value > 1}

This keeps your code compact and clean while still performing a loop.

Iterating Over Nested Dictionaries

Dictionaries can hold other dictionaries as values. When this happens, you need a loop inside a loop.

python

CopyEdit

nested_dict = {

'fruits': {'apple': 10, 'banana': 5},

'vegetables': {'carrot': 3, 'beetroot': 7}

}

for category, items in nested_dict.items():

print(f"{category}:")

for item, quantity in items.items():

print(f" {item}: {quantity}")

This works well when dealing with structured data or configurations. Just be careful with indentation—readability becomes more important here.

Iterating Using dict.keys() and Accessing Values Separately

This approach might look like a step back, but it's useful when you want to modify the values during the loop or need conditional logic that works better with the key-value split.

python

CopyEdit

for key in my_dict.keys():

value = my_dict[key]

print(f"{key}: {value}")

It’s slightly longer but gives you control over when and how you access values.

Iterating With a Function

If you’re using a dictionary and want to apply the same logic to every pair, you can wrap the logic inside a function and call it inside the loop.

python

CopyEdit

def print_item(key, value):

print(f"{key} has value {value}")

for key, value in my_dict.items():

print_item(key, value)

This keeps your loop short and pushes the work into a reusable function, which can be helpful in larger projects.

Iterating Using zip() on keys() and values()

If you want to loop through keys and values together, but prefer not to use .items(), you can combine .keys() and .values() with zip(). This gives you the same result but through a different structure.

python

CopyEdit

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}

for key, value in zip(my_dict.keys(), my_dict.values()):

print(f"{key}: {value}")

This works well and gives you the same output as .items(). It's a bit less efficient than using .items() because it creates two iterators, but it can be useful when you want to pair elements from two separate iterable views of the dictionary.

Final Words

Python gives you more than one way to loop through a dictionary. Some are clean and direct, while others are better for specific situations like working with sorted data or nesting. Whether you're filtering, transforming, printing, or just accessing items, you can pick the one that matches your goal without needing to reach for anything extra. Just keep your code readable and choose the method that makes your logic clear to anyone else looking at it.

Advertisement

Recommended Updates

Technologies

Efficient Ways to Check for Element Existence in a Python List

Alison Perry / May 09, 2025

Discover different methods to check if an element exists in a list in Python. From simple techniques like using in to more advanced methods like binary search, explore all the ways to efficiently check membership in a Python list

Technologies

8 Reasons Generative AI Security Problems Are Escalating

Tessa Rodriguez / May 20, 2025

Think generative AI risks are under control? Learn why security issues tied to AI models are growing fast—and why current defenses might not be enough

Technologies

Understanding matplotlib.pyplot.subplots(): Build Better Layouts in Python

Alison Perry / May 07, 2025

Learn how to use matplotlib.pyplot.subplots() in Python to build structured layouts with multiple charts. A clear guide for creating and customizing Python plots in one figure

Technologies

The Complete Guide to Sorting DataFrames in Pandas

Tessa Rodriguez / May 11, 2025

Want to organize your pandas DataFrame without confusion? This guide shows clear, practical ways to sort by values, index, custom logic, or within groups

Technologies

Pega GenAI Blueprint: Key Features, Uses, and Benefits

Alison Perry / May 27, 2025

Explore Pega GenAI Blueprint's top features, practical uses, and benefits for smarter business automation and efficiency.

Technologies

New York Times Vs OpenAI Lawsuit: Top 7 Ways It Impacts Media

Alison Perry / May 27, 2025

Explore how the New York Times vs OpenAI lawsuit could reshape media rights, copyright laws, and AI-generated content.

Technologies

Amazon's AI Image Tools Could Give Advertisers a Boost

Alison Perry / May 28, 2025

Amazon explores AI-generated imagery to create targeted, efficient ads and improve marketing results for brands.

Technologies

Understanding __init__ in Python: A Beginner’s Guide to Class Setup

Alison Perry / May 10, 2025

Learn how __init__ in Python works to initialize objects during class creation. This guide explains how the Python class constructor sets instance variables, handles defaults, and simplifies object setup

Technologies

How Rabbit R1 Can Improve Workflow in Enterprise Settings

Alison Perry / May 21, 2025

Explore how Rabbit R1 enhances enterprise productivity with AI-powered features that streamline and optimize workflows.

Technologies

How the OpenAI GPT Store Helps Developers Share Custom GPTs

Tessa Rodriguez / May 27, 2025

Explore how developers utilize the OpenAI GPT Store to build, share, and showcase their powerful custom GPT-based apps.

Technologies

Domino Data Lab Aims for Responsible Generative AI Growth

Alison Perry / May 27, 2025

Domino Data Lab introduces tools and practices to support safe, ethical, and efficient generative AI development.

Technologies

8 Industries That Will Benefit Most from AI-Powered Contact Centers

Tessa Rodriguez / May 26, 2025

Discover top industries for AI contact centers—healthcare, banking fraud detection, retail, and a few others.