×

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

OSError in Python

Python: 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 is said...

4 minutes read.

Python ord() Function

Python ord() Function The ord() function in Python returns the number representing the Unicode code of a specified character. Syntax ord(c) Parameter c: This parameter represents a string or any character. Return This function returns the number...

1 minute read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Filter List in Python

Python: Python is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a user-friendly programming...

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

Python Function A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a...

7 minutes read.

Python String isdigit() method

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

2 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Continue and Pass Statements in Python

Difference between continue and pass statements in Python The tasks can be repeated and automated efficiently using loops in Python. Sometimes we have to exit from the entire loop completely, we...

2 minutes read.

Python String endswith() method

Python String endswith() method The string.endswith() method in Python returns a Boolean value True if the string ends with the specified suffix, otherwise it returns False. Syntax endswith(suffix[, start[, end]]) Parameter suffix – This parameter represents a string or tuple...

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

Python String count() method

Python String count() method The string.count() method returns the number of times a specified value appears in the string. Syntax string.count(sub[, start[, end]]) Parameter sub: This parameter represents a substring to be searched. start: This parameter...

1 minute read.

CSV Write in Python

What is meant by CSV? CSV stands for Comma Separated Values. The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in...

3 minutes read.

Python Packages

A package is a collection of Python modules that share a similar namespace and are generated by putting all of the modules in a single directory with certain special files...

6 minutes read.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.

String indices must be integers in Python

Lists, tuples, and strings are examples of iterable objects in Python whose items or characters can be retrieved by their index numbers. For instance, you might take the following action to...

3 minutes read.