×

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example.

Introduction to Dictionary in Python

Dictionary is a special type of data structure in Python. It is an unordered collection of data, with data being stored with a key and value pairs. Dictionaries in Python can be created by giving them a name, and the key-value pairs can be declared inside the curly braces {}. There is no limit on the number of key-value pairs expressed in a single dictionary; there can be as many as a minimum being one to a maximum n number of key-value pairs. The value of the key in a dictionary can be of any data type, with no restriction on that part. 

A comma can differentiate each key-value pair. The unique thing about dictionaries is that the key-value pair can be duplicated as often as we want. An important point to remember is that the Dictionary, when declared twice with the same variable name, then the Dictionary that is stated at the end will be printed when the print function is used on them. There is no compulsory rule that a dictionary must always be declared with key-value pair in it; we can even declare an empty dictionary and then pass values later in future too. 

The key-value pair then can be pushed by passing through the index number; also, the values and keys can be accessed using the index number. Accessing the elements can be accessed using the get() function. This get function returns the value of the element when the key of the particular key is passed as an argument inside the braces of the get function. One of the other most popular methods to access the elements is using the loop, either a for loop or a while loop.

See the below code for reference for creating a sample dictionary.

Code:

sample_dictionary = {


    'Name' : 'javatpoint',
    'location':'internet',
    'achievement':'best website to learn programming'


}


print(sample_dictionary)

Output

{'Name': 'javatpoint', 'location': 'internet', 'achievement': 'best website to learn programming'}

How to Iterate using different methods through a Dictionary in Python

There are multiple ways and built-in methods to iterate through a dictionary in Python.

Some of them are given below:

1. using the build keys function.

2. without using the build key function.

3. using the dot values function.

4. iterating through key-value pairs using the items function.

5. without using the items function to iterate through the key-value pairs.

6. Printing the elements of the dictionary which are (key-value) pair.

Let us now discuss each method to iterate through a dictionary in detail.

Using the Build-Keys() Function Method:

Observe the below code carefully

Code

StatesAndCapitals = {


    'Telangana' : 'Hyderabad',
    'Tamilnadu' : 'Chennai'


}
keys = StatesAndCapitals
print(keys)

Output

{'Telangana': 'Hyderabad', 'Tamilnadu': 'Chennai'}

Exaplanation:

Here in the above code, we see variable named states and capitals is created as a dictionary in which two elements are created. The key here is the states' names, and the values are the capitals of the respective states. After the Dictionary is made, another variable named keys is declared in which the name of the dictionary dot keys function is declared. When the newly created function is printed, which is key in this case as the name rightly tells when the print function is executed, the keys of the Dictionary are printed on the output screen.

Without using the Build Key Function

If we are not using the built-in functions in the Python programming language, then the only possible way is by iterating the Dictionary using a for or a while loop.

See the below code for reference to iterate through a dictionary

Code:

StatesAndCapitals = {


    'Telangana' : 'Hyderabad',
    'Tamilnadu' : 'Chennai'


}


for states in StatesAndCapitals:
    print(states)

Output

Telangana
Tamilnadu

Using the Dot Values Function.

In the above two methods, we have seen the keys being printed, but by using the dot values function, we can print the values of the Dictionary.

See the below code for reference.

Code

StatesAndCapitals = {


    'Telangana' : 'Hyderabad',
    'Tamilnadu' : 'Chennai'


}


for states in StatesAndCapitals.values() :
    print(states)

Output

Hyderabad
Chennai

Iterating through Key-Value Pairs using the Items Function

In the above cases, we have seen how to print keys and values of the Dictionary separately, but by using the items function in Python, we can print both of them together. 

See the below code for reference:

Code

StatesAndCapitals = {


    'Telangana' : 'Hyderabad',
    'Tamilnadu' : 'Chennai'


}


for states in StatesAndCapitals.items() :
    print(states)

Output

('Telangana', 'Hyderabad')
('Tamilnadu', 'Chennai')

Without using the Items Function to Iterate through the Key-value Pairs

As an optimization to the above way to print the key-value pair, we can also iterate through the Dictionary using the for loop.

See the below code for reference to iterate through the dictionary.  

Code

StatesAndCapitals = {


    'Telangana' : 'Hyderabad',
    'Tamilnadu' : 'Chennai'


}


for i in StatesAndCapitals :
    print(i , 'capital is' , StatesAndCapitals[i])

Output

Telangana capital is Hyderabad
Tamilnadu capital is Chennai

Printing the Elements of the Dictionary (Key-Value) Pair

As we have seen in the above cases, we have printed the key-value pair using a built-in function and a for loop separately; we will combine both.

See the below code for reference.   

Code

StatesAndCapitals = {


    'Telangana' : 'Hyderabad',
    'Tamilnadu' : 'Chennai'


}


keys = StatesAndCapitals.items()
print(keys)

Output

dict_items([('Telangana', 'Hyderabad'), ('Tamilnadu', 'Chennai')])

Related Topics

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

Python pow() Function

Python pow() Function The pow() function in Python return the parameter ‘x’ to the power ‘y’ and if the parameter ‘z’ is present, it returns x to the power y, modulo z (computed more efficiently than pow(x, y) % z). Syntax pow(x, y[, z]) Parameter x: This parameter represents the base...

1 minute read.

Python program to count the number of a substring in a string

Python program to count the number of a substring in a string A part of the string is called a substring. This article explains the Python program to find how many...

1 minute read.

Python sort() function

Python provides many built-in functions for solving many problems that arise in different situations in programs. One of such methods is the sort () method. In this article, the syntax...

4 minutes read.

Magento 2 Site optimization

Magento 2 Site optimization Magento 2 is a CMS, commonly referred to as Intensive efficiency. Improving the speed and reliability of your Magento 2 app helps clients to achieve a better user experience while...

2 minutes read.

Python If-else statement

In real life, there are situations where we have to make decisions for a particular circumstance and based on those decisions, and we plan our next move. The same thing...

4 minutes read.

Python String split() method

The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is...

2 minutes read.

Python String find() method

Python String find() method The string.find() method in Python finds the first occurrence of the specified value and returns the lowest index in the string if the substring sub is found else it...

2 minutes read.

Find Median of List in Python

The median is an enlightening measurement that is utilized as a proportion of the focal inclination of a circulation. It is equivalent to the centre worth of the conveyance. There...

3 minutes read.

How to append a string in python

Adding or appending a string to another string is easy in Python. It is called concatenation and is a basic concept of strings in almost all programming languages. Ways to Append...

4 minutes read.

Gaussian elimination in python

Linear and polynomial equations are used in almost all fields of numerical simulation. However, its most common use in engineering is in the area of linear system analysis. The broader...

3 minutes read.

Python program to sort the array element into ascending order

Python program to sort the array element into ascending order In this example, we'll see how to sort the array elements in ascending order using a Python program. Sorting is a...

2 minutes read.

Import Module in Python

In this article, you will learn everything about “ Import ” in Python. Modules in python that are already created can be accessed and used in another code by importing the...

6 minutes read.

Anaconda python 3.7 download for windows 10 64-bit

Before installing Anaconda, you need to first know what Anaconda actually is. Anaconda is an IDE (Integrated development environment) platform used to code and executes python programs. Anaconda works both online...

3 minutes read.

Python Control Statements

Control statements are under the roof topic of loops and loops in python are defined as iteratively and repeatedly working on source code. Loop control statements are defined as they...

3 minutes read.

GUI Calendar using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Operator Module In Python

Introduction The operator module is used for performing operations using methods rather than utilizing operators in Python code. The operator module provides several methods for performing the operations.  The operator module contains...

7 minutes read.