This post will discuss how to iterate over a dictionary in Python.

1. Using Dictionary Iterators

One of the simplest ways to iterate over a dictionary in Python is to use dictionary iterators. By default, when we iterate over a dictionary using the for loop, we get the keys of the dictionary. Here is an example of how to use dictionary iterators to iterate over the keys of a dictionary:

Download  Run Code

Output:
(‘A’, 1)
(‘B’, 2)
(‘C’, 3)

 
Note that keys are iterated over in the same order as the insertion order. The for x in d is shorthand for for x in d.keys(), but much faster. We can make it more explicit and readable than the default iteration over a dictionary by using the keys() function:

Download  Run Code

2. Using items() function

The dictionary iterators only loops over the keys in the dictionary. To iterate over both keys and values, we can use the items() function, which returns a view of key-value pairs of the dictionary as tuples. We can then use the for loop to iterate over this view object and unpack each tuple into two variables: one for the key and one for the value. Here is an example:

Download  Run Code

Output:
(‘A’, 1)
(‘B’, 2)
(‘C’, 3)

That’s all about iterating over a dictionary in Python.