How do I iterate over dicts in Python with examples?

In Python, dictionaries are versatile data structures that allow for the storage of key-value pairs. Iterating over dictionaries is straightforward and can be done in several ways depending on what you need. Below are common methods to iterate over dictionaries.

Python, dictionaries, iterate, key-value pairs
Learn how to effectively iterate over dictionaries in Python using various methods such as iterating through keys, values, or both.
# Example 1: Iterating over keys my_dict = {'a': 1, 'b': 2, 'c': 3} for key in my_dict: print(key) # Output: a, b, c # Example 2: Iterating over values for value in my_dict.values(): print(value) # Output: 1, 2, 3 # Example 3: Iterating over key-value pairs for key, value in my_dict.items(): print(key, value) # Output: a 1, b 2, c 3

Python dictionaries iterate key-value pairs