A dictionary is made up of a set of key-value pairs. Each key-value combination corresponds to a key and its corresponding value. When working with dictionaries, you may want to iterate across the stored values. For example, we want the Students data, which includes information such as name, age, address, course details, cellphone number, and so on. We’d like to iterate through the dictionary, storing that data so you may present it to your program’s user. Learn dictionaries using for loop here.
There are several ways to iterate through a dictionary. This article will show you how to use a for loop to iterate through a dictionary.
Iterate over Dictionaries using for loop
Dictionaries are iterable objects, which means they can be traversed in the same way that any other object can. A Python for loop is probably the simplest technique to traverse through a dictionary. This loop allows you to iterate through each value in the dictionary one at a time.
Example 1: Access both key and value using items()
The items() method should be used to loop through the dictionary’s key and values. The items() method returns a list of tuples, each of which is a key-value pair. We can either iterate it directly or by using it along with the for loop.
Example
my_dict = {'Name': 'Sam', 'Age': 26, 'City': 'Toronto', 'Degree': 'Masters'}
# Method 1
print(my_dict.items())
print('')
# Method 2
print('Dictionary Key-Value pairs are:')
for i in my_dict.items():
   print(i)
Output
dict_items([('Name', 'Sam'), ('Age', 26), ('City', 'Toronto'), ('Degree', 'Masters')])
Dictionary Key-Value pairs are:
('Name', 'Sam')
('Age', 26)
('City', 'Toronto')
('Degree', 'Masters')
Example 2: Access both key and value without using items()
Python’s dictionary iterates over the keys by default. Python returns an iterator through the keys of a dictionary when we execute a for loop on it.
Example
my_dict = {'Brand': 'Audi', 'Segment': 'SUV', 'Color': 'Blank', 'Price': 9000000}
print('Dictionary Key-Value pairs are:')
for i in my_dict:
   print(i, '->', my_dict[i])
Output
Dictionary Key-Value pairs are:
Brand -> Audi
Segment -> SUV
Color -> Blank
Price -> 9000000
Example 3: Access both key and value using iteritems()
The iteritems() function works only for the Python 2 versions.
Example
my_dict = {'Title': 'My World', 'Author': 'David Brown', 'Edition': '3rd', 'Pages': 389, 'Price': '$19.99'}
print('Dictionary Key-Value pairs are:')
for key, value in my_dict.iteritems():
   print(key, '->', value)
Output
Dictionary Key-Value pairs are:
Title -> My World
Author -> David Brown
Edition -> 3rd
Pages -> 389
Price -> $19.99
Example 4: Return keys or values explicitly
You may want to iterate solely through the keys or only through the values of a dictionary at times. You can use keys() and values() to return the dictionary’s keys and values explicitly.
Example
my_dict = {'Fruit': 'Apple', 'Vegetable': 'Cabbage', 'Flower': 'Rose', 'Snack': 'Wafers'}
print('Dictionary Keys are:')
for k in my_dict.keys():
   print(k)
print('')
print('Dictionary Values are:')
for v in my_dict.values():
   print(v)
Output
Dictionary Keys are:
Fruit
Vegetable
Flower
Snack
Dictionary Values are:
Apple
Cabbage
Rose
Wafers
Example 5: Iterate a List of Dictionaries
Python allows you to nest one sort of data structure inside another. To iterate such a data structure, we must first iterate through the outer data structure (in this case, a list) and then nest the iteration of the inner data structure elements (dictionary).
Example
users = [{'Name': 'Sean', 'Profession': 'Businessman', 'Education': 'MBA'},
        {'Name': 'David', 'Profession': 'Teacher', 'Education': 'Literature'},
        {'Name': 'John', 'Profession': 'Programmer', 'Education': 'MS'}]
#function to iterate and print dictionary line by line Â
def iterate_dict(dictionary, ident=3):
   print('{')
   for key, value in dictionary.items():
       print(' '*ident, key, ": ", value)
   print('}')
#iterate through the outer list
for dict in users:
   #pass the inner dictionary to the iteration method
   iterate_dict(dict)
Output
{
Name :Â Sean
Profession :Â Businessman
Education :Â MBA
}
{
Name :Â David
Profession :Â Teacher
Education :Â Literature
}
{
Name :Â John
Profession :Â Programmer
Education :Â MS
}
Leave a Reply