For Loop Over Keys and Values in a Python Dictionary

Dictionaries are one of the most useful data structures in the Python programming language. A Python dictionary is used to store data in the form of key and value pairs. Most Python newbies get confused when iterating through a dictionary because the data is stored in key and value pairs. So if you want to learn how to use a for loop on the keys and values of a Python dictionary, this article is for you. In this article, I’ll show you a tutorial on using a for loop on keys and values in a Python dictionary.

Using For Loop Over Keys and Values in a Python Dictionary

Let’s create a Python dictionary and use a for loop to see where exactly beginners face problems:

age = {"Aman": 23, "Akanksha": 24, "Sajid": 22, "Hardik": 21}
for i in age:
    print(i)
Aman
Akanksha
Sajid   
Hardik 

In the above code, I have created a Python dictionary that contains the names as the keys and age as the values. While iterating over it using a for loop, it gives only the keys as an output. But this is not a proper way of using a for loop on a Python dictionary. To iterate over the keys of a dictionary, you should use the keys() method as shown in the code below:

for i in age.keys():
    print(i)
Aman
Akanksha
Sajid
Hardik

Similarly, to iterate over the values of a dictionary, you should use the values() method as shown in the code below:

for i in age.values():
    print(i)
23
24
22
21

In some cases, you want to iterate over both the keys and values of a dictionary, in such cases, you should use the items() method as shown in the code below:

for key, value in age.items():
    print(f'Name: {key}, Age: {value}')
Name: Aman, Age: 23
Name: Akanksha, Age: 24
Name: Sajid, Age: 22
Name: Hardik, Age: 21

So this is how you can use a for loop over a dictionary in Python.

Summary

Dictionaries are one of the most useful data structures in the Python programming language. They are used to store data in the form of key and value pairs. I hope you liked this article on how to use a for loop on the key and value of a dictionary in Python. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

AI/ML Engineer | Published Author. My aim is to decode data science for the real world in the most simple words.

Articles: 2106

Leave a Reply

Discover more from AmanXai by Aman Kharwal

Subscribe now to keep reading and get access to the full archive.

Continue reading