How to loop over a dictionary using Python• 1 min
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 will get you a tuple (key, value) for every key:value pair.
Which you can print directly as an element if written like so:
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: