Blog Post #37: Iterating with Style: Looping Through Lists and Dictionaries

We now have a solid understanding of both for and while loops (Post #34, Post #36). We know that for loops are the perfect tool for iterating over sequences, and so far, we’ve mostly used them with strings and the range() function.

In this post, we’re going to get a sneak peek at how to loop through two of Python’s most important data structures: lists and dictionaries. While we’ll cover these in great detail in Part 3, understanding the looping patterns now will make you a more effective programmer and prepare you for the kinds of data you’ll see in the real world.

Looping Through a List

First, what is a list? In simple terms, a list is an ordered collection of items, defined with square brackets [] and separated by commas.

Looping through a list is the most straightforward use case for a for loop. The loop will go through the list one item at a time, from the first to the last, assigning each item to your temporary variable.

Let’s look at a practical example where we calculate the sum of a list of expenses.

expenses = [12.50, 8.00, 21.75, 5.25]
total = 0.0

# The for loop will iterate through each item in the expenses list
for expense in expenses:
    print(f"Adding {expense} to the total...")
    total += expense # Using the shorthand operator from Post #19

print(f"\nTotal expenses: ${total:.2f}")

On each pass of the loop, the expense variable holds the next value from the list (12.50, then 8.00, and so on), which we then add to our total.

Looping Through a Dictionary

Next, what is a dictionary? A dictionary is a collection of key: value pairs, defined with curly braces {}. They are used for storing related pieces of data, where each value is accessed by its unique key or label.

player_stats = {'name': 'Gandalf', 'level': 20, 'class': 'Wizard'}

The Default: Looping Through Keys

If you use a for loop on a dictionary directly, it will iterate through the keys by default.

print("Player Stats:")
for stat_key in player_stats:
    # 'stat_key' will be 'name', then 'level', then 'class'
    value = player_stats[stat_key] # We use the key to look up the value
    print(f"  {stat_key}: {value}")

The Best Way: Using the .items() Method

While looping through keys works, Python provides a much more direct and readable way to get both the key and the value at the same time: the .items() method.

When you loop over my_dictionary.items(), Python gives you both the key and the value in each iteration. We can capture them with a special syntax: for key, value in ....

print("\nPlayer Stats (the better way):")
for key, value in player_stats.items():
    # On the first pass, key='name' and value='Gandalf'
    # On the second pass, key='level' and value=20, and so on.
    print(f"  {key}: {value}")

This method is cleaner, more explicit, and is the preferred, “Pythonic” way to loop through a dictionary.

What’s Next?

You’ve now seen the standard patterns for looping through lists and dictionaries. For lists, a simple for item in list is all you need. For dictionaries, using the .items() method to get both the key and value is the most Pythonic approach.

So far, our loops have always run to completion, either by iterating through every item or by the while condition becoming false. But what if you need to exit a loop early, before it’s finished? For example, what if you’re searching for an item in a list and you find it on the third try? There’s no need to check the rest of the list. In Post #38, we will learn how to take control of our loops by exiting them early with the break statement.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment