What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

04 Methods to Iterate through a Dictionary in Python (with code)

  • Dec 23, 2022
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abrar Ahmed
04 Methods to Iterate through a Dictionary in Python (with code)

During programming, we have learned about data structures and how we can make use of them in accessing and storing data. Data structures are used over a wide range of applications from storing a list to storing encoded hash values.

But there is a particular data structure in python that offers functionality that no other data structure does. This data structure is called the dictionary. It is a powerful data structure that allows you to store key and value pairs in python under one name.

In this tech blog, we will learn How to iterate a dictionary in Python?

What is a Dictionary?

Dictionaries can be thought of as a written map of various objects. Let us simplify this even further with an example. Say that we want to buy a car. There are three cars in the market, a Toyota Supra, a Nissan Skyline, and a Dodge Charger.

All these cars have their respective owners, A, B, and C. Now if we wanted to see any of these cars first we would have to talk to the owners first then we could see the car. So we can say that the owner is the key to seeing the car and the car is the value we are interested in.

Python dictionaries allow you to create an elaborate data structure to store key-value pairs and access them using the same name. We can create dictionaries in python by enclosing keys and their respective values within curly braces.

We could also use the dict() method to create a dictionary. Dictionaries in python are mutable and new values can be accessed and removed. Items within a dictionary can be accessed using their keys:


Dictionary_name[key]

dict1 = {"key1":1,"key2":3}
print(dict1["key1"])

 

Output:

1

 

Here is a simple image to understand what is a Dictionary:

Key Value in Dictionary in Python

Dictionaries are mutable and they can be altered as per the needs of the program. Dictionaries allow new values to be added to the dictionary in a very simple manner. Have a look at the code below:

dict1 = {"key1":1,"key2":2}
print(dict1)
dict1["key3"]=3
print(dict1)

 

Output:

{'key1': 1, 'key2': 2}
{'key1': 1, 'key2': 2, 'key3': 3}

 

In the code, we have a dictionary, dict1. When we need to add a new item to the dictionary, we simply write a new name in the square braces we use to access values inside the dictionary, then we assign it a new value.

If the key we specify already exists in the dictionary, then a new key will not be created, rather the value for the existing key will get updated with the new value we passed to it.

04 Methods to Iterate over a Dictionary in Python

Now that we know what a dictionary is, let us see how we can iterate over a dictionary.

Iteration is an operation that we often do in coding for simple operations like searching for an element, or sorting a data structure, to complex tasks like breadth-first search and depth-first search. Iterating over a dictionary can be done in multiple ways as mentioned below:

01) Using the .keys() method

The .keys() method is useful when we want a list of all the keys that are present inside a dictionary. The .keys() method can be used to iterate not just over all the keys within the dictionary but also over all the values present in the dictionary since keys can be used to access the values.

We pass the .keys() method as the iterable argument in the for loop of python, as shown in the code below:

dict1 = {"key1":1,"key2":2,"key3":3}
for key in dict1.keys():
    print(key,":",dict1[key])

 

Output:

key1 : 1
key2 : 2
key3 : 3

 

We can also implement this method without using the .keys() method. The code for this is given below:

dict1 = {"key1":1,"key2":2,"key3":3}
for i in dict1:
    print(i,":",dict1[i])

 

Output:

key1 : 1
key2 : 2
key3 : 3

 

Here, the loop variable 'i' by default gets the key values in every iteration and then we use the key to get the value it was assigned to.

02) Using the .values() method

What if we directly wanted to access all the values inside a dictionary without making use of the keys? There is a way for that. We can use the .values() method to get an iterable of all the values that are stored inside the dictionary. Then using a for loop we can iterate over this iterable.

One thing we should keep in mind is that we cannot access the keys that the values are stored against using this method.

dict1 = {"key1":1,"key2":2,"key3":3}
for val in dict1.values():
    print(val)

 

Output:

1
2
3

 

03) Using the .items() method

What if we wanted to access the key and value pairs together? We can use the .items method. It returns a list that contains both the keys and the values. The way to access it is by using two loop variables inside the for loop, the example code explaining this method is given below:

dict1 = {"key1":1,"key2":2,"key3":3}
for key,val in dict1.items():
    print(key," : ",val)

 

Output:

key1  :  1
key2  :  2
key3  :  3

 

What we are doing in this code is using the key loop variable to hold the key value and the value loop variable to hold the value that we receive from the .items() method.

04) Unpacking a dictionary

As we know, dictionaries are a collection of key and value pairs. We can use the * operator on a dictionary to unpack it. Let us look at the code first to understand this concept:

dict1 = {"key1":1,"key2":2,"key3":3}
print("The dictionary is\nKey1:{key1}\nKey2:{key2}\nKey3:{key3}".format(*dict1,**dict1))

 

Output:

The dictionary is
Key1:1
Key2:2
Key3:3

 

In this code, the dictionary we have is dict1. When we say, *dict1, we get all the key values that are stored in the dictionary. After that when we say **dict1, we get all the values that are stored in the dictionary. This method is called unpacking the dictionary.

Conclusion

Dictionaries are a collection of key-value pairs and these pairs can be iterated over in various manners. We can use the keys to iterate over a dictionary in python or we could also use the values. 

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abrar Ahmed
An ambivert individual with a thirst for knowledge and passion to achieve. Striving to connect Artificial Intelligence in all aspects of life. I am also an avid coder and partake in coding challenges all the time on Leetcode and CodeChef.