Skip to main content

How to iterate over a dictionary in Python

How to iterate over a dictionary in Python.

Here's a detailed step-by-step tutorial on how to iterate over a dictionary in Python:

Step 1: Create a dictionary

First, you need to create a dictionary in Python. A dictionary is a collection of key-value pairs enclosed in curly braces {}. Each key-value pair is separated by a colon :. The keys in a dictionary are unique, and they can be of any immutable data type (e.g., strings, numbers, tuples), while the values can be of any data type.

Here's an example of a dictionary:

my_dict = {
"name": "John",
"age": 25,
"city": "New York"
}

Step 2: Iterate using a for loop

To iterate over a dictionary, you can use a for loop. The for loop allows you to loop through each key in the dictionary.

Here's an example of iterating over the dictionary using a for loop:

for key in my_dict:
print(key)

Output:

name
age
city

Step 3: Access the values

To access the corresponding values of each key during iteration, you can use the key inside square brackets [] to access the value associated with that key.

Here's an example of accessing the values during iteration:

for key in my_dict:
value = my_dict[key]
print(key, value)

Output:

name John
age 25
city New York

Step 4: Iterate using items() method

Python provides a built-in method called items() that returns a view object containing the key-value pairs of the dictionary. You can use this method to iterate over both keys and values simultaneously.

Here's an example of iterating over a dictionary using the items() method:

for key, value in my_dict.items():
print(key, value)

Output:

name John
age 25
city New York

Step 5: Iterate using keys() method

If you only need to iterate over the keys of a dictionary, you can use the keys() method. It returns a view object containing the keys of the dictionary.

Here's an example of iterating over the keys using the keys() method:

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

Output:

name
age
city

Step 6: Iterate using values() method

Similarly, if you only need to iterate over the values of a dictionary, you can use the values() method. It returns a view object containing the values of the dictionary.

Here's an example of iterating over the values using the values() method:

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

Output:

John
25
New York

That's it! You now know how to iterate over a dictionary in Python using different methods. Feel free to experiment with your own dictionaries and utilize these techniques in your code.