Tuesday 30 January 2024

Looping over the dictionary using items() method in Python

Using items() method, we can iterate over a dictionary.

>>> emp_dict = {'id' : 1, 'name' : 'Krishna', 'age' : 34}
>>> 
>>> for key, value in emp_dict.items():
...   print(f'{key} --> {value}')
... 
id --> 1
name --> Krishna
age --> 34

 

Above code demonstrates how to iterate over a dictionary and print its key-value pairs.

 

emp_dict = {'id' : 1, 'name' : 'Krishna', 'age' : 34}

This line creates a dictionary named emp_dict. A dictionary in Python is a collection of key-value pairs. Here, the dictionary represents an employee with three pieces of information: their 'id' (which is 1), 'name' (which is 'Krishna'), and 'age' (which is 34).

 

for key, value in emp_dict.items():

This line starts a for loop. The .items() method is called on the dictionary emp_dict. This method returns a view object that displays a list of dictionary's (key, value) tuple pairs.

 

In each iteration of the loop, key and value will be assigned to the corresponding pair of items from the dictionary. For instance, in the first iteration, key will be 'id' and value will be 1, in the second iteration, key will be 'name' and value will be 'Krishna', and so on.

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment