×

Traverse Dictionary in Python

Traversing a dictionary is visiting each and every step in the dictionary, which is also called iterating the dictionary

In Python, dictionaries are a useful and commonly used data structure in which we have key-value pairs

Traversing a dictionary explains how to operate on a dictionary's key-value pairs while traversing through it.

There are many ways to traverse the dictionary in python

1. Using the items() method

2. Using the keys() method

3. Using the values() method

4. Using the Index to Iterate

1. Using the items() method

We can loop through the dictionary using Python's dict.items() method. You will learn the value and the key to each thing with each iteration.

Let ‘s see the examples using the items() method

Example 1

dictionary = { 
   'sravani': 'mamidgi', 
   'yamini': 'nallakunta', 
   'glory': 'parshapalli', 
   'chandana': 'ranabothu', 
   'shivapriya': 'thalla'
   }
for keys, values in dictionary.items(): 
print(keys ,values)

output

sravanimamidgi
yamininallakunta
glory parshapalli
chandanaranabothu
shiva priyathalla

Example 2

dictionary = { 
   'Name': 'sravani', 
   'year': '2003', 
   'age': '19', 
   'locatiion': 'Zaheerabad' 
}


for keys, values in dictionary.items(): 
print(keys ,values)

output

Name sravani
year 2003
age 19
locatiionZaheerabad

2. Using the keys() method

Use the keys() method that the dictionary provides to iterate through all of its keys. A list of the keys found in the dictionary is returned as an iterable.

Let ‘s see the examples using the items() method

Example 1

dictionary = { 
   'Name': 'sravani', 
   'year': '2003', 
   'age': '19', 
   'locatiion': 'Zaheerabad' 
}


for keys in dictionary.keys(): 
   print(keys)

output

Name
year
age
location

Example 2

dictionary = { 
   'sravani': 'mamidgi', 
   'yamini': 'nallakunta', 
   'glory': 'parshapalli', 
   'chandana': 'ranabothu', 
   'shivapriya': 'thalla'
   }
for keys in dictionary.keys(): 
   print(keys)

output

sravani
yamini
glory
chandana
shiva Priya

3. Using the values() method

Use the dictionary's values() method to loop through the values of the dictionary's elements.

The dictionary returns an iterable that contains all of the values for each entry. Then, by utilizing a for loop, you can cycle over the numbers as seen below.

Let ‘s see the examples using the items() method

Example 1

dictionary = { 
   'sravani': 'mamidgi', 
   'yamini': 'nallakunta', 
   'glory': 'parshapalli', 
   'chandana': 'ranabothu', 
   'shivapriya': 'thalla'
   }
for values in dictionary.values(): 
   print(values)

output

mamidgi
nallakunta
parshapalli
ranabothu
thalla

example 2

dictionary = { 
   'Name': 'sravani', 
   'year': '2003', 
   'age': '19', 
   'locatiion': 'Zaheerabad' 
}
for values in dictionary.values(): 
   print(values)

output

sravani
sravani
2003
19
Zaheerabad

4. Using the Index to Iterate

To iterate across the dictionary, use the item’s index. This is comparable to iterating the dictionary without using the methods keys(), values(), or items.

Let ‘s see the examples using the items() method

Example 1

dictionary = { 
   'Name': 'sravani', 
   'year': '2003', 
   'age': '19', 
   'locatiion': 'Zaheerabad' 
}
for index in dictionary:
print(index, dictionary[index])

output

Name sravani
year 2003
age 19
locatiionZaheerabad

Example 2

dictionary = { 
   'sravani': 'mamidgi', 
   'yamini': 'nallakunta', 
   'glory': 'parshapalli', 
   'chandana': 'ranabothu', 
   'shivapriya': 'thalla'
   }
for index in dictionary:
print(index, dictionary[index])

output

sravanimamidgi
yamininallakunta
glory parshapalli
chandanaranabothu
shiva priyathalla

Traversing over a dictionary in alphabetical order

Usually, dictionaries don't maintain any kind of structure. This suggests that the order of the elements in the iteration is not guaranteed. To iterate a dictionary using a specified order, use Python's sorted() method. The item will initially be sorted before being traversed through by a for a loop.

Example 1

Dictionary keys are sorted by the function sorted(dictionary.keys()), and for iterates through the keys that were returned.

Here is an example of iterating through an index-based dictionary

dictionary = { 
   'sravani': 'mamidgi', 
   'yamini': 'nallakunta', 
   'glory': 'parshapalli', 
   'chandana': 'ranabothu', 
   'shivapriya': 'thalla'
   }
for keys in sorted(dictionary.keys()):
print(keys, dictionary[keys])

output

chandanaranabothu
glory parshapalli
shiva priyathalla
sravanimamidgi
yamininallakunta

Example 2

dictionary = { 
   'Name': 'sravani', 
   'year': '2003', 
   'age': '19', 
   'locatiion': 'Zaheerabad' 
}


for keys in sorted(dictionary.keys()):
print(keys, dictionary[keys])

output

Name sravani
age 19
locatiionZaheerabad
year 2003

Combine the value and the key unlike using items()

In this illustration, a Python Loop Through 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.

Example 1

dictionary = { 
   'Name': 'sravani', 
   'year': '2003', 
   'age': '19', 
   'locatiion': 'Zaheerabad' 
}


for i in dictionary: 
   print(i,'->',dictionary[i])

output

Name ->sravani
year -> 2003
age -> 19
locatiion ->Zaheerabad

example 2

dictionary = { 
   'sravani': 'mamidgi', 
   'yamini': 'nallakunta', 
   'glory': 'parshapalli', 
   'chandana': 'ranabothu', 
   'shivapriya': 'thalla'
   }
for i in dictionary: 
   print(i,'->',dictionary[i])

output

sravani ->mamidgi
yamini ->nallakunta
glory ->parshapalli
chandana ->ranabothu
shiva priya ->thalla

Related Topics

Multiple Linear Regression using Python

Linear Regression: Linear regression is a method that models the relationship between a dependent variable and one or more independent variables; in other terms, that models the relationship between a target...

6 minutes read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

How to get current date in python?

How to get current date in python? In Python programming language, date and time are not just a data form, but it is possible to import a method called datetime to operate...

3 minutes read.

Arguments and parameters in Python

Generally, there is a misunderstanding that parameters and arguments, both are the same. But, as a programmer, you need to understand the difference between these two. Parameters: While defining a function, we...

5 minutes read.

Reverse a String 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.

What is Sleeping Time in Python

Did you ever postpone a Python program's execution? Usually, you want your code to execute as quickly as possible. But there are times when it is in your best interests...

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

What is Collaborative Filtering in ML, Python

Introduction Contents recommendation is a useful tactic for almost any specific technology looking to increase interest, but it frequently calls for a lot of user data and perhaps laborious content tagging...

3 minutes read.

Python BS4 Code

Python BS4 Code The BS4 stands for BeautifulSoup version 4.x. The BeautifulSoup is a Python library which is used for pulling out data of the HTML & XML files using the...

14 minutes read.

Amazon rekognition using python

Amazon recognition service is an AI service which is an image labelling API (Application programming interface). In this article, we shall learn to use the AWS python boto3 module to...

3 minutes read.

After Python, What Should I Learn

Python is a programming language used to create websites, software, and other projects. It is easy to code and easy to learn. After learning Python, there are many different directions...

4 minutes read.

How to Pass a list as an Argument in Python

Lists in Python A list is a datatype in python which is used to store the data in a sequence. The lists are mutable; that is, we can change the values...

3 minutes read.

How to get Time in seconds in Python

Python's time module source shows that are based on time. The time() method is used by developers and returns the current time as a UNIX timestamp. A UNIX timestamp is...

4 minutes read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

Working with CSV files in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

7 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 minutes read.

List Comprehension in Python

Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known...

5 minutes read.

Raise Exception in Python

Most of the programmers/developers create large programs to solve complex tasks in Python. The code can be of 1000 lines and even more based on the need of the problem....

5 minutes read.