×

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 Modules

Python Modules The Python module is a collection of definition and statements. It can contain functions, classes, and variables.  Combining the related code into a module makes the code easier to understand and use....

5 minutes read.

Cross Validation in Sklearn

Data scientists can benefit from cross-validation in machine learning in two key ways: it can assist in minimising the amount of data needed and ensure the artificial intelligence model is...

14 minutes read.

Python Pass Statement

The pass statement is a null statement. The difference between pass and comment is that comment is ignored by the interpreter, whereas pass is not. The pass statement is typically used...

3 minutes read.

Nested for Loop in Python

"Loop" is one of the foundation concepts to learn programming in any language. Nested loops are significant steps in solving many types of problems, ranging from basic to complex scenarios....

9 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 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.

Python Tricks: The Book

A Buffet of Awesome Python Features Dan Bader is the author of the book called Python Tricks . he is the owner and editor of Real Python and one of the...

3 minutes read.

Compound Interest GUI Calculator 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...

6 minutes read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute 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.

Sentiment Analysis using NLTK

Introduction Data is being produced at an astounding rate and volume in the field of the internet and other digital services nowadays. Researchers, engineers, and data analysts often work with tabular...

7 minutes read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Expressions in Python

What is Expression in Python? The expression contains more than one operator as well as the operands with it. Expression helps us to produce some other values. In the Python programming...

12 minutes read.

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.

Python math.cos and math.acos function

Math.cos() function In Python, the Math module is used for performing the mathematical operations. It includes the math.cos() function that is used for obtaining the cosine value of an angle in...

3 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.

Paramiko Python Example

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.

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 minutes read.

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples. Any variable holds a value in...

4 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.