×

Python Loop through a Dictionary

Introduction

in this tutorial, we will discuss in python How to Loop Through a Dictionary.

In contrast to other Data Types, which can only retain a single value as an element, a Dictionary in Python can have a key: value pair. It is used to store the data values like a map.

In Python, there are numerous ways to iterate through a dictionary.

  • Utilizing the build.keys(), access the key
  • Without utilizing the key(), access the key
  • loop via all values using.values()
  • loop via all keys, and value pair utilizing items()
  • value without utilizing items() and access both key
  • Printing elements as a pair in Key-Value

Dictionary Refresher

Key-value structures are used to store data in Python dictionaries. This indicates that a key is given to each value that can be utilized to refer to that specific item.

Here is an illustration of a Python dictionary:

book = {
	'Title': 'The Omnivore’s Dilemma: A Natural History of Four Meals',
	'Author': 'MichaelPollan',
	'Date_ published': 2006,
	'In_stock': True
}

The keys and values in our dictionary are denoted by colons (:), which are used throughout. The keys, in this example title, author, date published, and in stock, are the words to the left of the colons. All of these keys have a string format.

Example 1: Utilizing the build.keys(), access the key

You'll see that in this example, we're using the in-built keys() method, which enables us to print every key in the dictionary.

Code:

# Iterating through each value in a dictionary using Python 3


states_And_Capitals = {
'Arunachal Pradesh' : 'Itanagar' ,
'Assam': 'Dispur' ,
'Bihar' : 'Patna' ,
'Chhattisgarh' : 'Raipur' ,
'Goa' : 'Panaji' ,
'Gujarat' : 'Gandhinagar' ,
'Haryana' : 'Chandigarh' ,
'Himachal Pradesh' : 'Shimla' ,
'Jharkhand' : 'Ranchi' ,
'Karnataka' : 'Bengaluru' ,
'Kerala' : 'Thiruvananthapuram' ,
'Madhya Pradesh' : 'Bhopal'
}


key = states_And_Capitals.keys()
print (key)

Output:

dict_keys(['Arunachal Pradesh', 'Assam', 'Bihar', 'Chhattisgarh', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh', 'Jharkhand', 'Karnataka', 'Kerala', 'Madhya Pradesh'])

Example 2: Without utilizing the key(), access the key

Using "for" loops to iterate over dictionaries allows us to iterate our keys and print every key found in the dictionary.

Code:

# Iterate through each key in a dictionary using Python 3


states_And_Capitals = {
'Arunachal Pradesh' : 'Itanagar' ,
'Assam': 'Dispur' ,
'Bihar' : 'Patna' ,
'Chhattisgarh' : 'Raipur' ,
'Goa' : 'Panaji' ,
'Gujarat' : 'Gandhinagar' ,
'Haryana' : 'Chandigarh' ,
'Himachal Pradesh' : 'Shimla' ,
'Jharkhand' : 'Ranchi' ,
'Karnataka' : 'Bengaluru' ,
'Kerala' : 'Thiruvananthapuram' ,
'Madhya Pradesh' : 'Bhopal'
}


print ('List Of given states:\n')


# Looping over keys
for state in states_And_Capitals:
 print(state)

Output:

List Of given states:


Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jharkhand
Karnataka
Kerala
Madhya Pradesh

Example 3: loop via all values using.values()

The values() method is being used in this example to print every value that is available in the dictionary.

Code:

# Iterating through each value in a dictionary using Python 3


states_And_Capitals = {
'Arunachal Pradesh' : 'Itanagar' ,
'Assam': 'Dispur' ,
'Bihar' : 'Patna' ,
'Chhattisgarh' : 'Raipur' ,
'Goa' : 'Panaji' ,
'Gujarat' : 'Gandhinagar' ,
'Haryana' : 'Chandigarh' ,
'Himachal Pradesh' : 'Shimla' ,
'Jharkhand' : 'Ranchi' ,
'Karnataka' : 'Bengaluru' ,
'Kerala' : 'Thiruvananthapuram' ,
'Madhya Pradesh' : 'Bhopal'
}


print ('List Of given capitals:\n')


# Looping over values
for capt in states_And_Capitals.values():
 print (capt)

Output:

List Of given capitals:


Itanagar
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Ranchi
Bengaluru
Thiruvananthapuram
Bhopal

Example 4: loop via all keys, and value pair utilizing items()

In this example, we'll use the items() method to output every key and value pair found in a dictionary.

Code:

# Iterating through each key-value pair in a dictionary using Python 3


states_And_Capitals = {
'Arunachal Pradesh' : 'Itanagar' ,
'Assam': 'Dispur' ,
'Bihar' : 'Patna' ,
'Chhattisgarh' : 'Raipur' ,
'Goa' : 'Panaji' ,
'Gujarat' : 'Gandhinagar' ,
'Haryana' : 'Chandigarh' ,
'Himachal Pradesh' : 'Shimla' ,
'Jharkhand' : 'Ranchi' ,
'Karnataka' : 'Bengaluru' ,
'Kerala' : 'Thiruvananthapuram' ,
'Madhya Pradesh' : 'Bhopal'
}


print ('List of given states, together with their capitals:\n')


# Looping over values
for state, capt in states_And_Capitals.items():
 print (state, ":", capt)

Output:

List of given states, together with their capitals:


Arunachal Pradesh : Itanagar
Assam : Dispur
Bihar : Patna
Chhattisgarh : Raipur
Goa : Panaji
Gujarat : Gandhinagar
Haryana : Chandigarh
Himachal Pradesh : Shimla
Jharkhand : Ranchi
Karnataka : Bengaluru
Kerala : Thiruvananthapuram
Madhya Pradesh : Bhopal

Example 5: value without utilizing items() and access both key

In this illustration, a Python Loop In via a Dictionary is used, and with each iteration, the directory's key is obtained. Next, key data is printed, and a key is used as an index to display values from the directory.

Code:

# Iterating through each value in a dictionary using Python 3


states_And_Capitals = {
'Arunachal Pradesh' : 'Itanagar' ,
'Assam'	: 'Dispur' ,
'Bihar' : 'Patna' ,
'Chhattisgarh' : 'Raipur' ,
'Goa' : 'Panaji' ,
'Gujarat' : 'Gandhinagar' ,
'Haryana' : 'Chandigarh' ,
'Himachal Pradesh' : 'Shimla' ,
'Jharkhand' : 'Ranchi' ,
'Karnataka' : 'Bengaluru' ,
'Kerala' : 'Thiruvananthapuram' ,
'Madhya Pradesh' : 'Bhopal'


}


for j in states_And_Capitals:
print(j, '->', states_And_Capitals[j])

Output:

Arunachal Pradesh -> Itanagar
Assam -> Dispur
Bihar -> Patna
Chhattisgarh -> Raipur
Goa -> Panaji
Gujarat -> Gandhinagar
Haryana -> Chandigarh
Himachal Pradesh -> Shimla
Jharkhand -> Ranchi
Karnataka -> Bengaluru
Kerala -> Thiruvananthapuram
Madhya Pradesh -> Bhopal

Example 6: Printing elements as a pair in Key-Value

In this example, the key value data is printed as pairs and each pair is contained within a dictionary.

Code:

# Iterating through each value in a dictionary using Python 3


states_And_Capitals = {
'Arunachal Pradesh' : 'Itanagar' ,
'Assam': 'Dispur' ,
'Bihar' : 'Patna' ,
'Chhattisgarh' : 'Raipur' ,
'Goa' : 'Panaji' ,
'Gujarat' : 'Gandhinagar' ,
'Haryana' : 'Chandigarh' ,
'Himachal Pradesh' : 'Shimla' ,
'Jharkhand' : 'Ranchi' ,
'Karnataka' : 'Bengaluru' ,
'Kerala' : 'Thiruvananthapuram' ,
'Madhya Pradesh' : 'Bhopal'
}


key = states_And_Capitals.items()
print(key)

Output:

dict_items([('Arunachal Pradesh', 'Itanagar'), ('Assam', 'Dispur'), ('Bihar', 'Patna'), ('Chhattisgarh', 'Raipur'), ('Goa', 'Panaji'), ('Gujarat', 'Gandhinagar'), ('Haryana', 'Chandigarh'), ('Himachal Pradesh', 'Shimla'), ('Jharkhand', 'Ranchi'), ('Karnataka', 'Bengaluru'), ('Kerala', 'Thiruvananthapuram'), ('Madhya Pradesh', 'Bhopal')])

Conclusion

There are numerous methods you can employ in Python to iterate through a dictionary. This tutorial covered the four methods for iterating over a dictionary in Python. We also looked at a real-world application of each of these techniques.


Related Topics

Python Statistical Module

Python Statistical Module The Python statistical module provides various functions that we can use in our Python program, to perform mathematical statistics operations on the numerical data given to us. The...

8 minutes read.

Python's Qstandarditemmodel

Python More interactive and user-friendly than any other programming language is Python. Many libraries are used by the python programming language to speed up procedures. Python can be used to develop...

3 minutes read.

Difference between Yield and Return in Python

Python yield statement 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...

3 minutes read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

__GETITEM__ and __SETITEM__ in Python

These methods are used in assignment operations, unary comparison operations, binary comparison operations and binary operations. These are pre-defined methods that perform many operations on a class instance. Examples like...

3 minutes read.

Python String encode() method

Python String encode() method The string.encode() method in Python returns an encoded version of the string. The default encoding is the current default string encoding Syntax String.encode([encoding[,errors]]) Parameter Encoding: This parameter represents a String specifying...

2 minutes read.

IPython Display

A command shell, often known as IPython is a software application that makes an operating system's features accessible to users or other applications. Based on the purpose and specific functioning...

6 minutes read.

How to Read html page in python

Html is a Hyper Text Markup language is a standard language used for creating webpages. HTML is the name of the language used to describe the construction of Web pages....

4 minutes read.

Difference Between Python and Scala

What is Python? Python is a high-level general-purpose interpreted programing language. It is used for multi general-purpose work such as language construct as well as its object-oriented approach aims to help...

4 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

What does base case mean in recursion

Base cases and recursive stages are used to define recursive functions. In a primary subject, we compute the outcome right away, given the function call's arguments. In a recursive step, we...

4 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

Gethostbyname() function in Python

Python Programming Language 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...

6 minutes read.

Difference between python list and tuple

In this tutorial, we will understand the key differences between python lists and tuples in python. Firstly, let us see the similarities between Lists and Tuples. Both are two data types...

4 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Python Program to Generate a Random String

The term "random" refers to a group of information or data that can be accessed in any chronological order. To create random strings, a Python program called random is utilized....

6 minutes read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.