×

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

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.

What is Ipython shell?

IPython is a command shell for computing in multiple programming languages. IPython was developed for python language by Fernando Perez in 2001 as a well-equipped python interpreter that offers shell...

3 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 Data Structures

Python Data Structures: Python is a programming language used worldwide for various fields such as building dynamic websites, artificial intelligence and many more. However, there is data that plays a...

18 minutes read.

any() Keyword in python

“any” keyword in python This page contains all the information about any () Keyword in python, how it is used with lists, tuples, dictionaries, sets, and what its function is? Python...

3 minutes read.

Python OOPs: Class, Object, Inheritance and Constructor

Basic Object-Oriented Programming (OOP) Concepts in Python Python is similar to most general-purpose programming languages with an Object-Oriented environment system since its existence. Being an Object-Oriented Programming language, Python provides ease...

9 minutes read.

Excel to CSV in Python

Define MS Excel Microsoft Excel is an application provided by the Microsoft corporation which allows us to build graphs to build tables, and it is also used for the macro programming...

4 minutes read.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms)...

3 minutes read.

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

Python range() function

Python range() function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Syntax range(stop)        or range(start, stop[, step]) Parameter start: It is...

1 minute read.

Isodate Python

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

3 minutes read.

Front end in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

4 minutes read.

Python String center() method

Python String center() method The center() method will center align the string, using a specified character (space is default) as the fill character. Syntax string.center(width[, fillchar]) Parameter width This parameter represents the length of the returned string. fillchar...

1 minute read.

PyShark in Python

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

4 minutes read.

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values. Syntax dictionary.fromkeys(sequence[, value]) Parameter sequence- This...

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

File Explorer using Tkinter in Python

File Explorer: Users can control folders and files on a device using an application known as a file manager or file explorer. Customers can access, edit, copy, delete, and start moving files...

3 minutes read.

Python Scikit-image | Image Processing Using Scikit-Image

What is Image Processing? The world is defined with images and, every image has its different specialties. An image can contain much-needed information that can be helpful in various ways. The process...

4 minutes read.

os.stat() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.