A Guide to Iterating Through Dictionary Key-Value Pairs with 5 Examples

A Guide to Iterating Through Dictionary Key-Value Pairs with 5 Examples

You can iterate over key-value pairs in a dictionary using a variety of methods in Python. Here are five examples:

  1. Using a simple for loop:
my_dict = {'a': 1, 'b': 2, 'c': 3}

for key, value in my_dict.items():
    print(key, value)
  1. Using dictionary unpacking in a for loop:
my_dict = {'a': 1, 'b': 2, 'c': 3}

for key, value in my_dict.items():
    print(key, value)
  1. Using the iteritems() method (in Python 2):
my_dict = {'a': 1, 'b': 2, 'c': 3}

for key, value in my_dict.iteritems():
    print(key, value)
  1. Using the iteritems() method and dictionary unpacking (in Python 2):
my_dict = {'a': 1, 'b': 2, 'c': 3}

for key, value in my_dict.iteritems():
    print(key, value)
  1. Using a generator expression:
my_dict = {'a': 1, 'b': 2, 'c': 3}

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

All these methods will iterate over the key-value pairs in the dictionary and allow you to perform operations on them within the loop.