Python dictionary type is used to store key-value pairs as items. The key
is used to identify value
where the key is unique. There are different ways to print dictionaries in a line-by-line or item-by-item way. In this tutorial, we examine methods to print dictionaries line by line like for Loop
, Iterating over Keys
, List Comprehension
, json.dumps()
.
Print Dictionary Using for Loop
The first method to print dictionary items is using the for loop with the dictionary items()
method. The items() method returns the items as a key-value tuple and these items can be iterated with for loop. In every step of for loop, the items can be printed like below. The key and value can be printed in different formats by using the print() function.
age = {"Mike":20,"John":30,"Ryan":25}
for key,value in age.items():
print(key," is ",value,"years old")
Mike is 20 years old John is 30 years old Ryan is 25 years old
Print Dictionary Iterating Over Keys
The dictionary can be used inside a for loop where the dictionary returns the key in every step. In the following example, we use the for loop in order to iterate over the keys and then use this key inside the for loop body to print the value of the key.
age = {"Mike":20,"John":30,"Ryan":25}
for key in age:
print(key," is ",age[key],"years old")
Print Dictionary Using List Comprehension
Python provides the ability to convert a dictionary to a list. List comprehension is a popular method in order to iterate over the list of items. So we can use the list comprehension by converting the dictionary into a list and iterating over the items using the list comprehension.
age = {"Mike":20,"John":30,"Ryan":25}
[print(key," is ",age[key],"years old") for key, value in age.items()]
Print Dictionary Using json.dumps()
The JSON is a popular data format used to transmit data between client and server. Python dictionary syntax and usage are very similar to the JSON and are used to express it in Python. The json
library provides the dump()
method in order to convert the dictionary into JSON format and print it to the terminal.
import json
age = {"Mike":20,"John":30,"Ryan":25}
print(json.dumps(age),indent=3)