Looping Through a Dictionary in Python: How to Iterate Through Keys and Values

Learn how to loop through a Python dictionary using a for loop. This guide demonstrates how to iterate through dictionary keys and access values, with practical examples for effective data handling.



Loop Through a Dictionary

You can loop through a dictionary by using a for loop.

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

# Print all key names in the dictionary, one by one
for x in thisdict:
  print(x)
Output

brand
model
year
Example

# Print all values in the dictionary, one by one
for x in thisdict:
  print(thisdict[x])
Output

Ford
Mustang
1964
Example

# Use the values() method to return values of a dictionary
for x in thisdict.values():
  print(x)
Output

Ford
Mustang
1964
Example

# Use the keys() method to return the keys of a dictionary
for x in thisdict.keys():
  print(x)
Output

brand
model
year
Example

# Loop through both keys and values using the items() method
for x, y in thisdict.items():
  print(x, y)
Output

brand Ford
model Mustang
year 1964