What is the method for iterating over dictionaries in Python?

There are a few ways to iterate through a dictionary in Python.

  1. list of keys
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict.keys():
    print(key, my_dict[key])
  1. list()
my_dict = {'a': 1, 'b': 2, 'c': 3}
for value in my_dict.values():
    print(value)
  1. – elements in a collection
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
    print(key, value)
  1. You can use list comprehension to convert the keys, values, or key-value pairs of a dictionary into a list, and then iterate over them. Below is an example code:
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = [key for key in my_dict.keys()]
values = [value for value in my_dict.values()]
items = [(key, value) for key, value in my_dict.items()]

These methods can be chosen based on actual needs to complete the traversal of the dictionary.

bannerAds