Blog Post #67: Looping Through Dictionaries: keys(), values(), and items()

In Post #65 and Post #66, we learned how to access individual items in a dictionary using square brackets [] and the .get() method. But what if we want to process all the information in a dictionary? For that, we need to know how to loop through it.

In this post, we’ll explore the three main ways to iterate over a dictionary: looping through its keys, its values, or its key-value pairs together.

For our examples, we’ll use this sample dictionary:

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

Method 1: Looping Through Keys

When you use a for loop on a dictionary directly, Python iterates over its keys by default.

print("Looping through keys (default):")
for key in user_profile:
    # We can use the key to look up the value
    value = user_profile[key]
    print(f"Key: {key}, Value: {value}")

For added clarity, you can be more explicit by using the .keys() method, which does the exact same thing. This can make your code more self-documenting, as it clearly states your intention.

print("\nLooping through keys explicitly with .keys():")
for key in user_profile.keys():
    print(key)

Both of these methods are useful when you need the keys to perform lookups or other operations.

Method 2: Looping Through Values with .values()

Sometimes, you only care about the values in a dictionary and don’t need the keys at all. For this, you can use the .values() method, which provides a view of all the values in the dictionary.

print("\nLooping through values only:")
for value in user_profile.values():
    print(value)

The output will be:

Looping through values only:
Alice
30
New York

Method 3: The Best of Both Worlds with .items()

Most of the time, you’ll want access to both the key and the value simultaneously during each iteration. The most Pythonic and efficient way to do this is with the .items() method.

The .items() method returns a view of the dictionary’s key-value pairs. Using the unpacking technique we learned in Post #60, we can capture both the key and the value in separate variables on each pass of the loop.

print("\nLooping through key-value pairs with .items():")
for key, value in user_profile.items():
    print(f"The user's {key} is {value}")

The output is clean and gives us everything we need:

Looping through key-value pairs with .items():
The user's name is Alice
The user's age is 30
The user's city is New York

This is the preferred method for iterating through a dictionary because it’s both readable and efficient. You get both the key and the value in one step, without needing to do a second lookup inside the loop.

What’s Next?

You now have a complete toolkit for iterating through dictionaries. You can loop through just the keys (the default), just the values with .values(), or both at once with .items(). Choosing the right method will make your code cleaner and more efficient.

You may have noticed that when we looped through our dictionary, the items appeared in the same order we defined them. This is a relatively new and very important feature of Python dictionaries. For a long time, this wasn’t the case. In Post #68, we will discuss this major change and what it means that Python dictionaries are now ordered.

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