Iterate over a dictionary in Python
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:
|
1 2 3 |
d = {'A': 1, 'B': 2, 'C': 3} for k in d: print((k, d[k])) |
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:
|
1 2 3 |
d = {'A': 1, 'B': 2, 'C': 3} for k in d.keys(): print((k, d[k])) |
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:
|
1 2 3 |
dict = {'A': 1, 'B': 2, 'C': 3} for k, v in dict.items(): print((k, v)) |
Output:
(‘A’, 1)
(‘B’, 2)
(‘C’, 3)
That’s all about iterating over a dictionary in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)