×

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

Is Python Case-sensitive when Dealing with Identifiers

Yes, Python is a case-sensitive language while dealing with identifiers. Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. It is a case-sensitive...

6 minutes read.

How to Open a File in Python with a Path?

File in Python File handling is an important operation; it allows the programmer to access the data in the files, such as text, binary values and excel sheets. The CSV files...

7 minutes read.

Iterate a Dictionary in Python – Part 2

In this tutorial, we will learn above various methods used to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to...

3 minutes read.

Check Palindrome in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Python Set isdisjoint() method

Python Set isdisjoint() method The set.isdisjoint() method in Python returns a boolean value True if two sets are disjoint sets ( i.e. none of the elements are present in both sets), otherwise it returns...

1 minute read.

Python pycountry

What is Pycountry? Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations...

4 minutes read.

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal We know that the most widely used number system is a decimal system, but the computer only understands binary values. The...

2 minutes read.

How to Import Files in Python

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to assign values to variables in Python and other languages?

Python makes it simple to construct variables. The value to be stored in the variable should then be written after a suitable name for the variable and the equality sign....

3 minutes read.

Python complex() class

Python complex() class The complex() class in Python returns a complex number or converts a string or number to a complex number. Syntax class complex([real[, imag]]) Parameter Real: This parameter consists of a number representing the real...

1 minute read.

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

How to Concat two Dataframes in Python

Using Pandas dataframe, we can concat two dataframes or series in Python. So let's take a brief introduction to what is Pandas in Python. Pandas is a library typically used for...

7 minutes read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.

Alexa Python

The cloud-based voice assistant renders text into speech in a female voice. Alexa is a virtual assistant released by Amazon. Using itself as a system for home automation, Alexa can...

4 minutes read.

How to create a login page in python

Users can access an application by providing their username and Password or by authenticating with a social media login on the login screen. Python Tkinter Python provides a variety of choices for...

3 minutes read.

Python Maurer Rose and Rhodonea Curves

In this tutorial, in Python we will make a Maurer Rose example and Rhodonea Curve example. Before we continue to see what precisely is maurer rose or a rhodonea bend...

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

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.

Spotify API in Python

The application programming interface is referred to as API. In essence, an API serves as a layer of communication or, as the name suggests, an interface that enables systems to...

3 minutes read.