Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to loop through a dictionary in Python

Introduction

Python is a versatile, powerful, and beginner-friendly programming language that offers a wide range of applications, from web development to data science. One of the most essential and commonly used data structures in Python is the dictionary. In this blog post, we will explore how to loop through a dictionary in Python, explaining concepts in a simple and jargon-free manner to help beginners better understand the topic.

What is a Dictionary?

In the real world, a dictionary is a reference book that contains words and their meanings. Similarly, in Python, a dictionary is a collection of key-value pairs, where each key is associated with a value. Dictionaries are unordered, changeable, and do not allow duplicate keys. They are ideal for situations where you need to store data in a way that allows for quick look-up based on a specific key.

Here's an analogy to help you grasp the concept: imagine that the keys are like names of people, and the values are their phone numbers. You can quickly look up someone's phone number based on their name in a phonebook.

Let's take a look at a simple example of a dictionary:

my_dictionary = {
    "apple": 1,
    "banana": 2,
    "orange": 3
}

This dictionary contains three key-value pairs, representing the quantity of fruits. The keys are the names of the fruits (apple, banana, and orange), and the values are their respective quantities (1, 2, and 3).

How to Loop Through a Dictionary in Python

Now that we understand what a dictionary is, let's discuss how to loop through it. Looping, also known as iteration, is the process of executing a block of code multiple times. In this case, we want to loop through all the key-value pairs in a dictionary.

There are three primary methods to loop through a dictionary in Python:

  1. Looping through keys
  2. Looping through values
  3. Looping through both keys and values

Let's discuss each method in detail with examples.

1. Looping Through Keys

To loop through the keys of a dictionary, you can use a for loop. The for loop in Python is used for iterating over a sequence (e.g., a list, tuple, or in this case, a dictionary). The general syntax for looping through dictionary keys is:

for key in my_dictionary:
    # perform some action with the key

Here's an example using our my_dictionary from earlier:

my_dictionary = {
    "apple": 1,
    "banana": 2,
    "orange": 3
}

for key in my_dictionary:
    print(key)

The output of this code will be:

apple
banana
orange

Note that the order of the keys may not be the same as in the original dictionary, as dictionaries are unordered.

2. Looping Through Values

If you want to loop through the values of a dictionary, you can use the .values() method. This method returns a view object that displays a list of all the values in the dictionary. The syntax for looping through dictionary values is:

for value in my_dictionary.values():
    # perform some action with the value

Here's an example using our my_dictionary:

my_dictionary = {
    "apple": 1,
    "banana": 2,
    "orange": 3
}

for value in my_dictionary.values():
    print(value)

The output of this code will be:

1
2
3

Again, remember that the order may not be the same as in the original dictionary.

3. Looping Through Both Keys and Values

If you want to loop through both the keys and values of a dictionary simultaneously, you can use the .items() method. This method returns a view object that displays a list of all the key-value pairs in the dictionary as tuples. The syntax for looping through dictionary keys and values is:

for key, value in my_dictionary.items():
    # perform some action with the key and value

Here's an example using our my_dictionary:

my_dictionary = {
    "apple": 1,
    "banana": 2,
    "orange": 3
}

for key, value in my_dictionary.items():
    print(key, value)

The output of this code will be:

apple 1
banana 2
orange 3

As with the other methods, keep in mind that the order may not be the same as in the original dictionary.

Advanced Techniques

Now that we've covered the basics of looping through a dictionary, let's discuss some advanced techniques that you may find helpful in various applications.

Looping Through a Dictionary in Sorted Order

Sometimes, you may want to loop through a dictionary in a specific order, such as sorted by keys. To do this, you can use the built-in sorted() function, which returns a sorted list of the specified iterable's elements (in this case, the dictionary's keys or values). The syntax for looping through a dictionary in sorted order is:

for key in sorted(my_dictionary):
    # perform some action with the key

Here's an example using our my_dictionary:

my_dictionary = {
    "apple": 1,
    "banana": 2,
    "orange": 3
}

for key in sorted(my_dictionary):
    print(key, my_dictionary[key])

The output of this code will be:

apple 1
banana 2
orange 3

In this case, the output is the same as the original dictionary, but the keys are guaranteed to be sorted.

Filtering While Looping Through a Dictionary

You can also filter the key-value pairs you want to loop through by adding a condition inside the loop. For example, if you only want to print the key-value pairs where the value is greater than 1, you can do the following:

my_dictionary = {
    "apple": 1,
    "banana": 2,
    "orange": 3
}

for key, value in my_dictionary.items():
    if value > 1:
        print(key, value)

The output of this code will be:

banana 2
orange 3

Conclusion

In this blog post, we have learned how to loop through a dictionary in Python, including looping through keys, values, and both keys and values simultaneously. We have also discussed advanced techniques such as looping through a dictionary in sorted order and filtering while looping.

Dictionaries are a powerful and widely used data structure in Python, and understanding how to loop through them is essential for anyone learning the language. By mastering these techniques, you'll be well on your way to becoming a proficient Python programmer.