How to Iterate Over a Dictionary in Python
Introduction
Dictionaries are one of the most used data structures in all of software development, and for a good reason. They allow us to store our data in neat key, value pairs, which in turn gives us the ability to, on average, access our data in O(1)
time.
While using a dictionary it’s important to know how to iterate over it. Not being able to recover the data you stored makes it practically useless.
In this article, we’ll see how to iterate through a Python dictionary with all kinds of iterators and the for
loop.
Using the keys() Method
Python dictionaries have a handy method which allows us to easily iterate through all initialized keys in a dictionary, keys()
.
Keep in mind that since Python 3, this method does not return a list, it instead returns a view object. A view object is exactly like the name