Different Ways to Iterate Dictionary in Python

1. Introduction

Iterating over dictionaries in Python is a common task that allows developers to access key-value pairs stored within. Python provides several methods to iterate through dictionaries, enabling developers to perform operations on dictionary items efficiently.

Definition

Iterating a dictionary in Python means accessing each key-value pair in the dictionary one by one. This can be done using various methods that Python dictionaries provide. These methods include iterating through keys, values, or both together.

2. Program Steps

1. Define a dictionary with some key-value pairs.

2. Iterate through the dictionary by keys.

3. Iterate through the dictionary by values.

4. Iterate through the dictionary by key-value pairs together.

5. Use dictionary comprehensions for iteration.

3. Code Program

# Step 1: Define a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Step 2: Iterate through the dictionary by keys
print("Keys:")
for key in my_dict:
    print(key)

# Step 3: Iterate through the dictionary by values
print("\nValues:")
for value in my_dict.values():
    print(value)

# Step 4: Iterate through the dictionary by key-value pairs
print("\nKey-Value Pairs:")
for key, value in my_dict.items():
    print(key, value)

# Step 5: Use dictionary comprehensions to create a new dictionary with modified values
new_dict = {k: v * 2 for k, v in my_dict.items()}

# Step 6: Print the new dictionary
print("\nNew Dictionary with Modified Values:")
print(new_dict)

Output:

Keys:
a
b
c
Values:
1
2
3
Key-Value Pairs:
a 1
b 2
c 3
New Dictionary with Modified Values:
{'a': 2, 'b': 4, 'c': 6}

Explanation:

1. my_dict is initialized with three key-value pairs.

2. The first loop iterates through the dictionary by keys, printing each key.

3. The second loop iterates through the dictionary by values(), printing each value.

4. The third loop iterates through the dictionary by items(), printing each key and value pair together.

5. A new dictionary new_dict is created using a dictionary comprehension that doubles each value.

6. new_dict is printed, showing that the values have been modified as per the comprehension.

Comments