Loop Through a Dictionary
A for loop works on dictionaries too.
What you get on each pass is a key of the dictionary, one at a time, but there are methods that return the values as well.
Example
Print each key name in turn:
Prompt
Write a Python program that creates a dictionary with three key-value pairs: brand Ford, model Mustang, year 1964.
Loop through the dictionary using a for loop and print all key names, one by one.
Output: complete Python program
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
Example
Print each value in turn, looking it up through its key:
Prompt
Write a Python program that creates a dictionary with three key-value pairs: brand Ford, model Mustang, year 1964.
Loop through the dictionary using a for loop and print all values, one by one, by referencing the keys.
Output: complete Python program
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])
Example
The values() method gets you the same values directly, so no key lookup is needed:
Prompt
Write a Python program that creates a dictionary with three key-value pairs: brand Ford, model Mustang, year 1964.
Use the values() method to loop through and print all values of the dictionary.
Output: complete Python program
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x)
Example
The keys() method is another way to get at the keys of a dictionary:
Prompt
Write a Python program that creates a dictionary with three key-value pairs: brand Ford, model Mustang, year 1964.
Use the keys() method to loop through and print all keys of the dictionary.
Output: complete Python program
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.keys():
print(x)
Example
Get keys and values together through items():
Prompt
Write a Python program that creates a dictionary with three key-value pairs: brand Ford, model Mustang, year 1964.
Use the items() method to loop through both keys and values, and print each key-value pair.
Output: complete Python program
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in thisdict.items():
print(x, y)