Loop through a dictionary

Just like you can do it with lists, you can use a for loop to loop through a dictionary. To do this, we need to create two variables in the for loop that will store the key and value of each key-pair. We then need to specify the name of the dictionary and use the items() method to return a list of key-value pairs.

Consider the following example:

my_dict = {'eye_color': 'blue', 'height': '165cm', 'weight': '54kg'}

for k,v in my_dict.items():
    print('The key is:',k,'and the value is:',v)

Inside the for loop we’ve defined the k and v variables that will be used for each key (the variable k) and value (the variable v) in the iterations. We’ve then used the items() method with the my_dict dictionary to loop through our dictionary.

These two variables that are usually used when looping through a dictionary are k (for keys) and v (for values). However, this is just a convention – you can use variable names of your choice.
Geek University 2022