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