×

Iterate a Dictionary in Python

In this tutorial, we will learn how to Iterate a Dictionary in Python.

Dictionary:

In Python, a dictionary is an unordered collection of data values that is used to store data values, in contrast to other data types which only allow a single value for an element to be stored.

Example:

Dict = {1: 'Hello', 2: 'Welcome', 3: 'Bye'}

Dictionary Methods:

clear() - Removes all of the dictionary's elements.

get() - Returns the value of a key that is specified.

pop() — Removes the element with the given key.

update() – Updates dictionary with provided key-value pairs.

Create a Dictionary:

By putting a series of components within curly brackets and separating them with a comma, one can build a dictionary in Python. Dictionary has two equivalent pair elements, among them, one is the Key and the other is value. A dictionary's values can be of any data type and can be replicated, but its keys must be immutable and cannot be repeated.

D = { <key>: <value>,<key>: <value>… <key>: <value>}
D = dict([(<key>, <value>),(<key>, <value) ... (<key>, <value>)])

Insert elements

Square brackets can be used to add an element to a dictionary.

The method dict.update()can be used to insert numerous entries at once. The dictionary is updated using the key/value pairs from other methods, overwriting any existing keys.

students['Jack'] = 10
students.update(['Jack' : 10])

Access Values

Since dictionaries are unordered containers, we are unable to retrieve dictionary values using a numerical index (like we can with lists or tuples). Instead, we use square brackets to encapsulate the key ([]). A KeyError is thrown if we try to retrieve a value using an unknown key.

We may utilise the method dict. Get to prevent receiving an exception for keys that are not specified (key[, default]). If the key is present in the dictionary, this method returns the value for the key; otherwise, the default is returned. It returns None if the default is not given (but never raises an exception).

print(dict.get('Student'))

Iteration:

There are several methods for iterating through a dictionary, they are

Using loops

We can use a for loop or any other Python loop to iterate over a dictionary. The loop variable will always contain the dictionary entry's key.

Code:

study={"school": "student", "collage ":” graduate”}
for x in study:
    print(x)          

Output:

School
collage

Loop through by Key and Value

To get a view object that lists all the (key, value) tuple pairs in a dictionary, use the items() method of the dict. Such that You may loop over the tuple to obtain the dictionary key and value.

Code:

study={"school": "student", "collage ":” graduate”}
for key, value in study.items():
    print(key, value)

Output:

school: student
collage: graduate

Use Key to get the Value

To obtain the value of the key, use dict[key].

Code:

study={"school": "student", "collage ":” graduate”}
for key in study:
    print(key, study[key])

Output:

school: student
collage: graduate

Use dict.keys()

We can use dict.keys() to iterate.

Example:

study={"school": "student", "collage ":” graduate”}
for key in study.keys():
    print(key)

Output:

school
collage

Use dict.values()

We can use dict.keys() to iterate.

Code:

study={"school": "student", "collage ":” graduate”}
for key in study.values():
    print(value)

Output:

student
graduate

Iterate with Index

Additionally, it is possible to iterate over a dictionary using the item's index, which is equivalent to doing so without utilising the methods keys(), values(), or items ().

study={"school": "student", "collage ":” graduate”}
for i in study:
    print(I, study[i])

Output:

1 student
2 graduate

Related Topics

Python Bubble Sort

Bubble sort is one of the techniques used to sort the elements in lists in a certain order, either in ascending or descending order. It is called Bubble sort because...

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

Standard GUI Unit Converter 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...

12 minutes read.

Python Modulo

For basic calculations, Python provides operators. Python supports a broad range of Arithmetic Operators to do arithmetic, as given below: +Addition*Multiplication-Subtraction/Division//Floor division**Exponentiation%Remainder/Modulus As you can see, one of these basic arithmetic operators...

8 minutes read.

Python AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

3 minutes read.

Pointers in Python

In this tutorial, we will study what pointers are and if they have any utility in python. Now, let us understand what pointers are Pointers Pointers are special variables used to store the...

3 minutes read.

Number Pattern Programs in Python

Learning Python is very easy, and it understands in better way compared to other programming languages. One of the many reasons why it has emerged as the most widely used...

4 minutes read.

Python Set difference_update() method

Python Set difference_update() method The set.difference_update() method in Python removes the items that exist in both sets. Syntax set.difference_update(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return None Example 1 # Python program explaining # the set.difference_update()...

2 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Python Permutations and Combinations

In mathematics, we all studied what is meant by permutations and combinations. “Permutations” define the way of arranging the elements in sequential order. “Combinations” mean the way of selecting the...

7 minutes read.

Python String capitalize() method

Python String capitalize() method The string.capitalize() method in Python returns a copy of the string with only its first character capitalized. Syntax string.capitalize() Parameter NA Return This function returns a string where the first character is upper...

1 minute read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.

PyDev with Python IDE

What is IDE? Integrated Development Environment is the abbreviation of IDE. It is a coding tool that automates code editing, finding errors and testing. IDE combines all the developer tools into...

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.

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

Python Call Function

In this article, you will learn about calling a function in Python. But before learning this, we should know about functions in Python.So, let’s get some overview of functions in...

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

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

Python next() function

Python next() function The next() function in Python retrieves the next item from the iterator.  Syntax next(iterator[, default]) Parameter iterable: It is a required parameter which represents an iterable object. default: This parameter represents a default value to...

1 minute read.