×

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

How to Install Tweepy in Python

In this article, we will learn or understand how to install Tweepy in Python and what Tweepy is. Firstly, let’s understand What Tweepy is. As we all know, one of the...

3 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Performing Transaction Using Python MySQL

Transaction A Transaction contains a set of SQL commands used to change the data in the dataset. If we say transaction, it means that the data in the database has changed....

3 minutes read.

Yield Statement In Python

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns back the...

2 minutes read.

Check whether dir is empty or not in python

Python: Check if a directory is empty In this tutorial, we will study how to check whether the director (dir) is empty or not in the python programming language. First of...

3 minutes read.

Python Set remove() method

Python Set remove() method The set.remove() method in Python removes the specified element from the set if it is present in the set else this method will raise an error if the specified item does...

2 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

Python String swapcase() method

Python String swapcase() method The string.swapcase() method in Python returns a copy of the string with uppercase characters converted to lowercase and vice versa. Syntax string.swapcase() Parameter NA Return This method returns a copy of the string...

1 minute read.

Anaconda in Python 3

What is Anaconda in Python 3? Anaconda is an open-source package combining Python and R programming languages used for data analytics and processing data. It consists of a huge number of...

4 minutes read.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.

Inheritance in Python

Inheritance in Python Object-Oriented Programming provides reusable patterns to the code for restricting the redundancy in development projects. One of the basic principles of Object-Oriented Programming that helps achieve recyclable code...

8 minutes read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Difference between Python and CPP

Difference between Python and C++ We all know that both C++ and Python are two of the most popular programming languages. Both C++ and Python shares some basic similarities such as...

6 minutes read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

Python Identifiers

Identifiers in Python User-defined names are identifiers in Python that are used to name variables, functions, classes, modules, and other things. You can create Python identifiers using these rules: As an identifier...

4 minutes read.

How to read data from com port in python

Comport, the I/O interface is known as a COM port that allows the connection for a serial device to a computer. COM ports are sometimes referred to as serial ports....

3 minutes read.

Python Parser

Introduction : Parsing is referred to as the processing and translation of a Python program into machine language. In general, we could indeed say that the command parse is used to...

4 minutes read.

Uint8 Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python String rjust() method

Python String rjust() method The string.rjust() method in Python returns a right-justified string of a given minimum width where the padding is done using the specified fillchar (default is a space). It returns...

2 minutes read.

Python property()

Python property() class The property() class in Python returns a property attribute. Syntax class property(fget=None, fset=None, fdel=None, doc=None) Parameter fget: This attribute is used for getting an attribute value. fset : This parameter sets an attribute value. fdel: It is a function for deleting...

1 minute read.