Skip to content

Write a Python program to print a dictionary line by line | Example code

  • by

Using two for loops with logic you can write a Python program to print a dictionary line by line. Iterate the dictionary with the key and value at the same time and print it.

for key, value in student_score.items():
    print(key, ' : ', value)

Python program to print a dictionary line-by-line

Simple example code.

cars = {'A': {'speed': 70,
              'color': 2},
        'B': {'speed': 60,
              'color': 3}}

for x in cars:
    print(x)
    for y in cars[x]:
        print(y, ':', cars[x][y])

Output:

Write a Python program to print a dictionary line by line

Source: stackoverflow.com

my_dict = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

for key, value in my_dict.items():
    print(f'{key}: {value}')

This program defines a dictionary called my_dict and then uses a for loop to iterate through its items (key-value pairs). Inside the loop, it prints each key and value using an f-string, which allows you to format the output nicely with the key and value separated by a colon. Each key-value pair is printed on a separate line.

Do comment if you have any doubts or suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading