Iterate over a dictionary using for loops in Python
In Python, dictionaries are unordered collections of data values that are stored as key-value pairs. Dictionaries are often used to store data that is connected in some way, such as the words in a book and their definitions.
One common task when working with dictionaries is to iterate over the keys, values, or both in the dictionary. This can be done using a for loop.
Iterating Over the Keys in a Dictionary
To iterate over the keys in a dictionary, you can use the for loop as follows:
# Define a dictionary d = {'cat': 'cute', 'dog': 'furry'} # Iterate over the keys in the dictionary for key in d: print(key)
This will output:
cat dog
If you want to access the values in the dictionary while iterating over the keys, you can use the items() method to return a tuple of the key-value pairs in the dictionary:
# Iterate over the keys and values in the dictionary for key, value in d.items(): print(key, value)
This will output:
cat cute dog furry
Iterating Over the Values in a Dictionary
To iterate over the values in a dictionary, you can use the values() method to return a list of the values in the dictionary, and then use a for loop to iterate over the list:
# Iterate over the values in the dictionary for value in d.values(): print(value)
This will output:
cute furry
If you want to access the keys in the dictionary while iterating over the values, you can use the items() method as before to return a tuple of the key-value pairs:
# Iterate over the keys and values in the dictionary for key, value in d.items(): print(key, value)
This will output:
cat cute dog furry
Iterating Over Both the Keys and Values in a Dictionary
To iterate over both the keys and values in a dictionary at the same time, you can use the items() method as shown above:
# Iterate over the keys and values in the dictionary for key, value in d.items(): print(key, value)
This will output:
cat cute dog furry