Printing Dictionary in Python

A dictionary is a data structure that stores key-value pairs. When you print a dictionary, it outputs pairs of keys and values.

Let’s take a look at the best ways you can print a dictionary in Python.

Print dictionary

The content of a Python dictionary can be printed using the print() function.

If you run the code, Python is going to return the following result:

{'brand': 'Toyota', 'model': 'Corolla', 'year': 2018}

Both keys and values are printed.

You can also use the dictionary method called items().

This function will display key-value pairs of the dictionary as tuples in a list.

dict_items([('brand', 'Toyota'), ('model', 'Corolla'), ('year', 2018)])

Printing with the for loop

items() can be used to separate dictionary keys from values. Let’s use the for loop to print the dictionary line by line.

If you run the code, the key-value pair will be printed using the print() function.

brand Toyota
model Corolla
year 2018

Print keys and values separately

With the items() method, you can print the keys and values separately.

for keys:

for values:

Python offers additional methods keys() and values() methods to achieve the same result.

keys() method:

values() method:

Using list comprehension to print dictionary

With a list comprehension, we can print a dictionary using the for loop inside a single line of code.

This code will return the contents of a dictionary line by line.

brand Toyota
model Corolla
year 2018

In a similar manner, you can also do list comprehension with keys() and values().

Output:

brand
model
year
Toyota
Corolla
2018

Prettyprint dictionaries as a table

If a dictionary becomes more complex, printing it in a more readable way can be useful. This code will display the dictionary as a table.

Inside the new dictionary, four elements represent multiple cars. The first part is a key, and the second part (value) is a list consisting of the brand of a car, its model, and its year of production.

The first print() function displays four headers: “Key”, “Brand”, “Model”, “Year”. Each of them is spaced by the number of characters from the previous column.

The same is done to the dictionary items. Each value is a list assigned to three variables: brand, model, and year, with the same amount of spacing.

If you run the code, you’ll see a dictionary displayed in a pretty tabular form.

Key   Brand      Model      Year      
11    Toyota     Corolla    2018      
2     Audi       A6         2014      
4     Citroen    C5         2009      
7     Ford       Focus      2017