w3resource

Python: Print a dictionary line by line

Python dictionary: Exercise-32 with Solution

Write a Python program to print a dictionary line by line.

Visual Presentation:

Python Dictionary: Print a dictionary line by line.

Sample Solution:

Python Code:

# Create a dictionary 'students' with student names as keys and nested dictionaries as values.
students = {'Aex': {'class': 'V', 'roll_id': 2}, 'Puja': {'class': 'V', 'roll_id': 3}}

# Iterate through the student names (keys) in the 'students' dictionary using a for loop.
for a in students:
    # Print the student name.
    print(a)
    
    # Iterate through the keys of the nested dictionary associated with the current student using a nested for loop.
    for b in students[a]:
        # Print the key, a colon, and the corresponding value from the nested dictionary.
        print(b, ':', students[a][b])

Sample Output:

Aex                                                                                                           
class : V                                                                                                     
rolld_id : 2                                                                                                  
Puja                                                                                                          
class : V                                                                                                     
roll_id : 3 

Python Code Editor:

Previous: Write a Python program to get the key, value and item in a dictionary.
Next: Write a Python program to check multiple keys exists in a dictionary.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.