×

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 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 String isalnum() method

Python String isalnum() method The string.isalnum () method in Python returns a boolean value true if all characters in the string are alphanumeric else for any other value it returns false. Syntax String.isalnum() Parameter NA Return This...

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

Python String isspace() method

Python String isspace() method The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given...

2 minutes read.

Python String split() method

The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is...

2 minutes read.

Managing Multiple Python Versions With pyenv

Introduction If you had ever wished to assist to an application that makes use of several different Python versions but weren't sure whether you would quickly test them all? Do you...

4 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

How to handle exceptions in python

Prerequisite: Exceptions and errors in Python What are Exceptions? Exceptions are run-time errors that unexpectedly occur and crash a program. When occurred, it alters the flow of the program. These errors are...

9 minutes read.

List Index out of Range Python for Loop

The List is generally used in Python to store multiple items or elements inside one single variable. The List is ordered in nature, the List can contain the elements inside...

3 minutes read.

Python e-book free download

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. There are many sources to learn python. In this...

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

Why learn Python?

All things considered, learning python would be extraordinary, it'll acquaint you with the universe of dynamic programming dialects, if you're somebody who has had a semester of involvement with C. Python...

4 minutes read.

Python Letter to Number

Python Letter to Number In this tutorial, we will convert the given letters into numbers using a Python. We will convert the given letter into the letter value as defined in...

3 minutes read.

Python Euclidean Distance

Euclidean distance is the distance between two points with whatever of dimensions. We are using NumPy library to find and calculate the Euclidean distance. The NumPy library is used for...

1 minute read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

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

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

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

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Python open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.

Python Data Types

Python Data Types: The variable in Python is used to store values, and they can hold different values. Each variable in Python has its own data-type. Since Python is a...

13 minutes read.