Python – Loop Dictionaries

In Python, dictionaries are mutable collections of key-value pairs, and you can loop through them in various ways. You can loop through the keys, values, or both keys and values using different methods.

Here are several ways to loop through dictionaries:


1. Looping Through Keys

By default, looping through a dictionary will iterate over its keys.

Example:

my_dict = {'a': 10, 'b': 20, 'c': 30}

# Loop through keys
for key in my_dict:
    print(key)

Output:

a
b
c

You can also explicitly use the keys() method to loop through the keys:

for key in my_dict.keys():
    print(key)

2. Looping Through Values

To loop through the values of a dictionary, you can use the values() method.

Example:

my_dict = {'a': 10, 'b': 20, 'c': 30}

# Loop through values
for value in my_dict.values():
    print(value)

Output:

10
20
30

3. Looping Through Both Keys and Values

To access both the keys and their corresponding values, you can use the items() method. This will give you a tuple with the key and value for each iteration.

Example:

my_dict = {'a': 10, 'b': 20, 'c': 30}

# Loop through both keys and values
for key, value in my_dict.items():
    print(f"Key: {key}, Value: {value}")

Output:

Key: a, Value: 10
Key: b, Value: 20
Key: c, Value: 30

4. Looping Through Keys and Modifying Values

You can also modify the values during iteration by directly referencing the key.

Example:

my_dict = {'a': 10, 'b': 20, 'c': 30}

# Modify values in the dictionary while looping
for key in my_dict:
    my_dict[key] = my_dict[key] * 2

print(my_dict)  # Output: {'a': 20, 'b': 40, 'c': 60}

5. Using Dictionary Comprehension

You can create a new dictionary using a loop with dictionary comprehension. This is useful for transforming a dictionary or filtering key-value pairs.

Example:

my_dict = {'a': 10, 'b': 20, 'c': 30}

# Create a new dictionary where values are doubled
new_dict = {key: value * 2 for key, value in my_dict.items()}
print(new_dict)  # Output: {'a': 20, 'b': 40, 'c': 60}

6. Looping with enumerate()

If you need to access both the index (position) and the key or value, you can use the enumerate() function.

Example:

my_dict = {'a': 10, 'b': 20, 'c': 30}

# Loop through keys and get the index as well
for index, (key, value) in enumerate(my_dict.items()):
    print(f"Index {index}: Key = {key}, Value = {value}")

Output:

Index 0: Key = a, Value = 10
Index 1: Key = b, Value = 20
Index 2: Key = c, Value = 30

Summary of Looping Methods:

  • Keys: Loop directly through the dictionary or use my_dict.keys().
  • Values: Use my_dict.values().
  • Both keys and values: Use my_dict.items().
  • Modifying values: Modify values directly by referencing the key during iteration.
  • Dictionary comprehension: Create new dictionaries using a loop expression.
  • Using enumerate(): Access both index and key-value pairs.
Leave a Reply 0

Your email address will not be published. Required fields are marked *