How do i print the contents of a dictionary in python?

In this article, we will discuss different ways to print line by line the contents of a dictionary or a nested dictionary in python.

As dictionary contains items as key-value pairs. So, first, let’s create a dictionary that contains student names and their scores i.e.

# A dictionary of student names and their score
student_score = {   'Ritika': 5,
                    'Sam': 7, 
                    'John': 10, 
                    'Aadi': 8}

Now to print this dictionary, we directly pass it in the print function i.e.

print(student_score)

the output will be like,

{'Ritika': 5, 'Sam': 7, 'John': 10, 'Aadi': 8}

Although it printed the contents of the dictionary, all the key-value pairs printed in a single line. If we have big dictionaries, then it can be hard for us to understand the contents. Therefore, we should print a dictionary line by line. Let’s see how to do that,

Advertisements

dict.items() returns an iterable view object of the dictionary that we can use to iterate over the contents of the dictionary, i.e. key-value pairs in the dictionary and print them line by line i.e.

# A dictionary of student names and their score
student_score = {   'Ritika': 5,
                    'Sam': 7, 
                    'John': 10, 
                    'Aadi': 8}

# Iterate over key/value pairs in dict and print them
for key, value in student_score.items():
    print(key, ' : ', value)

Output:

Ritika  :  5
Sam  :  7
John  :  10
Aadi  :  8

This approach gives us complete control over each key-value pair in the dictionary. We printed each key-value pair in a separate line.

Frequently Asked Questions

How to print all keys of a python dictionary?

How to print all values of a python dictionary?

How to print all key-value pairs of a python dictionary?

How to pretty print nested dictionaries in python?

All you need to know about Priting dictionaries

We can iterate over the keys of a dictionary one by one, then for each key access its value and print in a separate line i.e.

# A dictionary of student names and their score
student_score = {   'Ritika': 5,
                    'Sam': 7, 
                    'John': 10, 
                    'Aadi': 8}

# Iterate over the keys in dictionary, access value & print line by line
for key in student_score:
    print(key, ' : ', student_score[key])

Output:

Ritika  :  5
Sam  :  7
John  :  10
Aadi  :  8

Although by this approach we printed all the key value pairs line by line this is not an efficient method as compared to the previous one because to access one key-value pair, we are performing two operations.

In a single line using list comprehension & dict.items(), we can print the contents of a dictionary line by line i.e.

# A dictionary of student names and their score
student_score = {   'Ritika': 5,
                    'Sam': 7, 
                    'John': 10, 
                    'Aadi': 8}

# Iterate over the key-value pairs of a dictionary 
# using list comprehension and print them
[print(key,':',value) for key, value in student_score.items()]

Output:

Ritika : 5
Sam : 7
John : 10
Aadi : 8

Learn more about Python Dictionaries

  • What is a Dictionary in Python ? Why do we need it?
  • 6 Different ways to create Dictionaries in Python
  • How to iterating over dictionaries in python.
  • Check if a key exists in dictionary
  • How to get all the keys in Dictionary as a list ?

  • How to Iterate over dictionary with index ?
  • How to remove a key from Dictionary?
  • How to find keys by value in Dictionary
  • How to filter a dictionary by conditions?
  • How to get all the Values in a Dictionary ?

In python, json module provides a function json.dumps() to serialize the passed object to a json like string. We can pass the dictionary in json.dumps() to get a string that contains each key-value pair of dictionary in a separate line. Then we can print that string,

import json

# A dictionary of student names and their score
student_score = {   'Ritika': 5,
                    'Sam': 7, 
                    'John': 10, 
                    'Aadi': 8}

# Print contents of dict in json like format
print(json.dumps(student_score, indent=4))

Output

{
    "Ritika": 5,
    "Sam": 7,
    "John": 10,
    "Aadi": 8
}

We passed the dictionary object and count of indent spaces in json.dumps(). It returned a json like formatted string. Remember to import the json module for this approach.

Now, what if we have a nested python dictionary?

Printing nested dictionaries line by line in python

Suppose we have a nested dictionary that contains student names as key, and for values, it includes another dictionary of the subject and their scores in the corresponding subjects i.e.

# Nested dictionary containing student names and their scores in separate subjects
student_score = {   'Mathew': { 'Math': 28,
                                'Science': 18,
                                'Econimics': 15},
                    'Ritika': { 'Math': 19,
                                'Science': 20,
                                'Econimics': 19},
                    'John': {   'Math': 11,
                                'Science': 22,
                                'Econimics': 17}
                }

If print this dictionary by passing it to the print() function,

print(student_score)

Then the output will be like,

{'Mathew': {'Math': 28, 'Science': 18, 'Econimics': 15}, 'Ritika': {'Math': 19, 'Science': 20, 'Econimics': 19}, 'John': {'Math': 11, 'Science': 22, 'Econimics': 17}}  

It printed all the contents in a single line. Therefore, it is tough to understand the contents. Now to print the contents of a nested dictionary line by line, we need to do double iteration i.e.

# Nested dictionary containing student names and their scores in separate subjects
student_score = {   'Mathew': { 'Math': 28,
                                'Science': 18,
                                'Econimics': 15},
                    'Ritika': { 'Math': 19,
                                'Science': 20,
                                'Econimics': 19},
                    'John': {   'Math': 11,
                                'Science': 22,
                                'Econimics': 17}
                }

# Iterate over key / value pairs of parent dictionary
for key, value in student_score.items():
    print(key, '--')
    # Again iterate over the nested dictionary
    for subject, score in value.items():
        print(subject, ' : ', score)

Output:

Mathew --
Math  :  28
Science  :  18
Econimics  :  15
Ritika --
Math  :  19
Science  :  20
Econimics  :  19
John --
Math  :  11
Science  :  22
Econimics  :  17

We first iterated over the items, i.e. key/value pairs of the dictionary, and for each pair printed the key. As value field is another dictionary, so we again iterated over the key-value pairs in this dictionary and printed its contents i.e. key/value pairs in separate lines.

We can do this in a single line using json module’s dumps() function i.e.

import json

# Nested dictionary containing student names and their scores in separate subjects
student_score = {   'Mathew': { 'Math': 28,
                                'Science': 18,
                                'Econimics': 15},
                    'Ritika': { 'Math': 19,
                                'Science': 20,
                                'Econimics': 19},
                    'John': {   'Math': 11,
                                'Science': 22,
                                'Econimics': 17}
                }


print(json.dumps(student_score, indent=4))

Output:

{
    "Mathew": {
        "Math": 28,
        "Science": 18,
        "Econimics": 15
    },
    "Ritika": {
        "Math": 19,
        "Science": 20,
        "Econimics": 19
    },
    "John": {
        "Math": 11,
        "Science": 22,
        "Econimics": 17
    }
}

How do I display the contents of a dictionary in Python?

Print a dictionary line by line using for loop & dict. items() dict. items() returns an iterable view object of the dictionary that we can use to iterate over the contents of the dictionary, i.e. key-value pairs in the dictionary and print them line by line i.e.

How do I print a dictionary value?

Python's dict. values() method can be used to retrieve the dictionary values, which can then be printed using the print() function.

How can I extract all values from a dictionary in Python?

Here are 3 approaches to extract dictionary values as a list in Python:.
(1) Using a list() function: my_list = list(my_dict.values()).
(2) Using a List Comprehension: my_list = [i for i in my_dict.values()].
(3) Using For Loop: my_list = [] for i in my_dict.values(): my_list.append(i).

How do I fetch values in a dictionary?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.