How to loop over a dictionary using Python
• 1 minDictionary 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])
my_dict = {
"firstname":"John",
"lastname":"Smith",
"age":34,
}
# We loop over the dict using keys
for key in my_dict.keys():
print(key, 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:
my_dict = {
"firstname":"John",
"lastname":"Smith",
"age":34,
}
# We loop over the dict using items
for key, value in my_dict.items():
print(key, value)
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.
my_dict = {
"firstname":"John",
"lastname":"Smith",
"age":34,
}
# We loop over the dict using values
for value in my_dict.values():
print(value)
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: