Loop Dictionaries

 

What You'll Learn: In this tutorial, you'll discover how to loop through a dictionary using a for loop. This helps you access and work with both keys and values effectively.

Looping Through Keys

When you loop through a dictionary, the return values are the keys of the dictionary.

Example Code:

python
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
for x in thisdict:
    print(x)

Output:

brand
model
year

Looping Through Values

You can also print all values in the dictionary by referring to each key.

Example Code:

python
for x in thisdict:
    print(thisdict[x])

Output:

Ford
Mustang
1964

Using the values() Method

Another way to loop through the values is to use the values() method.

Example Code:

python
for x in thisdict.values():
    print(x)

Output:

Ford
Mustang
1964

Using the keys() Method

You can use the keys() method to loop through the keys of a dictionary.

Example Code:

python
for x in thisdict.keys():
    print(x)

Output:

brand
model
year

Looping Through Both Keys and Values

To loop through both keys and values, use the items() method.

Example Code:

python
for x, y in thisdict.items():
    print(x, y)

Output:

brand Ford
model Mustang
year 1964

Try It Yourself: Fun Exercises

  1. Your Favorite Books:
    • Create a dictionary of your favorite books and their authors.
    • Loop through the dictionary and print each book title and its author.
  2. List Your Favorite Movies:
    • Write a dictionary of movies and their release years.
    • Loop through the dictionary to print each movie and its release year using the items() method.

Summary:

In this Python tutorial, we learned how to loop through dictionaries using different methods. These include looping through keys, values, and both keys and values using the items() method. These techniques allow you to access and work with dictionary data efficiently. Keep experimenting and have fun with dictionaries in Python!