Write a Python program to iterate over dictionaries using for loops


The program creates a dictionary d with four key-value pairs. Two for loops are used to iterate through the key-value pairs in the dictionary. In the first loop, the items() method is used to retrieve a list of tuple pairs from the dictionary, and the loop uses tuple unpacking to assign the key and value of each pair to the variables k and v, respectively. The print statement inside the loop prints the key and value of each pair on separate lines.

In the second loop, the items() method is used again to retrieve a list of tuple pairs, but this time the loop simply iterates over the tuples without unpacking them. The print statement inside the loop prints each tuple on a separate line. Both loops produce the same output, but the first loop provides more control over the formatting of the output.

In summary, the program demonstrates two ways to iterate through the key-value pairs in a dictionary in Python, using the items() method and either tuple unpacking or direct iteration over the tuples.

Source Code

d={"Name":"Ram" , "Age":23 , "City": "Salem", "Gender": "Male"}
 
for k, v in d.items():
    print(k,' : ',v)
 
for i in d.items():
    print(i)

Output

Name  :  Ram
Age  :  23
City  :  Salem
Gender  :  Male
('Name', 'Ram')
('Age', 23)
('City', 'Salem')
('Gender', 'Male')