How to loop over a dictionary using Python
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Dictionary cannot be looped over like usual lists. Since they contain pair:value elements you will need to go through each key to loop over a dictionary.
Here is how to loop over a dictionary in Python.
Using the keys
Using the .keys() method you will loop over the keys.
In order to get the value corresponding to the pair you will need to use the key at every step. (e.g. my_dict[key])
Using items
Using items will get you a tuple (key, value) for every key:value pair.
Which you can print directly as an element if written like so:
Using values
You might end up needing the values only. The values() method is the one to go as it will directly give you a list of all the values contained in the dictionary.
Here you are! You now know how to loop over a dictionary in Python.
More on fundamentals
If you want to know more about Python fundamentals without headaches... check out the other articles I wrote by clicking just here:
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚