Iterate Through a Dictionary in Python

In Python, there are several ways to iterate through a dictionary depending on what you want to access (keys, values, or both). Here are the most common methods:

(1) Iterate through keys (default)

By default, iterating over a dictionary will give you its keys.

For example:

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for key in my_dict:
    print(key)

Output:

a
b
c
d

You can also explicitly use the keys() method to achieve the same result.

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

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

(2) Iterate through values

If you only need the values, you can use the values() method.

For example:

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for value in my_dict.values():
    print(value)

Output:

1
2
3
4

(3) Iterate through both keys and values (items)

To get both keys and values, you can use the items() method.

For example:

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for key, value in my_dict.items():
    print(f"Key: {key} Value: {value}")

Output:

Key: a Value: 1
Key: b Value: 2
Key: c Value: 3
Key: d Value: 4

(4) Iterate through dictionary with index

If you need the index along with the key-value pairs, you can use the enumerate() function.

For example:

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for index, (key, value) in enumerate(my_dict.items()):
    print(f"Index: {index} Key: {key} Value: {value}")

Output:

Index: 0 Key: a Value: 1
Index: 1 Key: b Value: 2
Index: 2 Key: c Value: 3
Index: 3 Key: d Value: 4