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:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
Output:
brand
model
yearLooping Through Values
You can also print all values in the dictionary by referring to each key.
Example Code:
for x in thisdict:
print(thisdict[x])
Output:
Ford
Mustang
1964Using the values() Method
Another way to loop through the values is to use the values() method.
Example Code:
for x in thisdict.values():
print(x)
Output:
Ford
Mustang
1964Using the keys() Method
You can use the keys() method to loop through the keys of a dictionary.
Example Code:
for x in thisdict.keys():
print(x)
Output:
brand
model
yearLooping Through Both Keys and Values
To loop through both keys and values, use the items() method.
Example Code:
for x, y in thisdict.items():
print(x, y)
Output:
brand Ford
model Mustang
year 1964Try It Yourself: Fun Exercises
- 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.
- 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!