In Python, you can iterate over the elements of a dictionary using a for loop. When you iterate over a dictionary using a for loop, the loop variable takes on the keys of the dictionary. You can then access the values of the dictionary using the keys.
Here's an example of iterating over a dictionary using a for loop:
fruits = {"apple": 1, "banana": 2, "cherry": 3}for fruit in fruits: print(fruit, fruits[fruit]) |
In this example, we define a dictionary fruits that contains the number of each fruit. We then use a for loop to iterate over the keys of the fruits dictionary. Inside the loop, we use the loop variable fruit to access the value of each key in the dictionary.
Alternatively, you can use the items() method to iterate over the keys and values of a dictionary together. Here's an example:
fruits = {"apple": 1, "banana": 2, "cherry": 3}for fruit, count in fruits.items(): print(fruit, count) |
In this example, we use the items() method to iterate over the keys and values of the fruits dictionary. The loop variable fruit takes on the keys of the dictionary, and the loop variable count takes on the values of the dictionary.