Iterating over a dictionary allows you to access and perform operations on its key-value pairs. Let’s explore different methods to iterate over a dictionary.
Method 1: Iterating over Keys
# Method 1: Iterating over Keys my_dict = {"name": "John", "age": 30, "city": "New York"} for key in my_dict: print(key, my_dict[key])
Output:
name John
age 30
city New York
Method 2: Iterating over Items
# Method 2: Iterating over Items my_dict = {"name": "John", "age": 30, "city": "New York"} for key, value in my_dict.items(): print(key, value)
Output:
name John
age 30
city New York