Iterate dictionary (key and value) with for loop in Python

Authors

In Python, to iterate the dictionary (dict) with a for loop, use keys(), values(), items() methods. You can also get a list of all keys and values in the dictionary with those methods and list().

Iterate over a dictionary with items()

To iterate over a dictionary with a for loop in Python, you can use the items() method to get the key-value pairs of the dictionary. Here is an example:

my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

for key, value in my_dict.items():
  print(key, value)

This code will print the following output:

apple 1
banana 2
orange 3

The items() method returns a sequence of tuples, where each tuple contains a key-value pair from the dictionary. The for loop assigns the first element of each tuple to the key variable and the second element of each tuple to the value variable, which are then used in the print() statement to print the key and value of each entry in the dictionary.

Iterate over dictionary with keys()

Another way to iterate over a dictionary with a for loop is to use the keys() method to get a sequence of the keys in the dictionary, and then use the in operator to check if each key is in the dictionary. Here is an example:

my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

for key in my_dict.keys():
  if key in my_dict:
    print(key, my_dict[key])

This code will also print the following output:

apple 1
banana 2
orange 3

In this case, the for loop iterates over the keys in the dictionary, and the if statement checks if each key is in the dictionary. If the key is in the dictionary, the print() statement prints the key and its corresponding value.

Iterate over dictionary with values()

Note that you can also use the dict.values() method to iterate over the values in a dictionary, and the dict.keys() and dict.values() methods can be used together to iterate over both the keys and values in a dictionary at the same time. For example:

my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

for key, value in zip(my_dict.keys(), my_dict.values()):
  print(key, value)

This code will also print the same output as the previous examples:

apple 1
banana 2
orange 3

The zip() function is used to combine the sequences of keys and values into a sequence of tuples, which are then iterated over by the for loop. Each tuple contains a key-value pair from the dictionary, and the for loop assigns the first element of each tuple to the key variable and the second element of each tuple to the value variable, which are then used in the print() statement to print the key and value of each entry in the dictionary.

TrackingJoy