Last updated: Apr 9, 2024
Reading timeยท3 min
To print a dictionary in table format:
print()
function to print the result.my_dict = { 1: ['alice', 29], 2: ['bobbyhadz', 30], 3: ['carl', 31], } headers = ['ID', 'Name', 'Age'] print(f'{headers[0]: <10}{headers[1]: <15}{headers[2]}') # ID Name Age # 1 alice 29 # 2 bobbyhadz 30 # 3 carl 31 for key, value in my_dict.items(): print(f'{key: <10}{value[0]: <15}{value[1]}')
We used a formatted string literal to format the headers and rows.
Formatted string literals also enable us to use the format-specific mini-language in expression blocks.
my_str = 'hi' # ๐๏ธ left-aligned result = f'{my_str: <6}' print(repr(result)) # ๐๏ธ 'hi ' # ๐๏ธ right-aligned result = f'{my_str: >6}' print(repr(result)) # ๐๏ธ ' hi'
The space between the colon and the less-than sign is the fill character.
The less-than or greater-than sign is the alignment.
We first format and print the headers and then iterate over the dictionary and print each row.
You can use the same approach to print a dictionary in table format if the dictionary doesn't have list values.
my_dict = { 'id': 1, 'name': 'bobbyhadz', 'age': 30 } # id 1 # name bobbyhadz # age 30 for key, value in my_dict.items(): print(f'{key: <10}{value}')
You can use the same approach if you need to use the dictionary's keys as headers in the table.
This is a three-step process:
dict.keys()
method to get a view of the dictionary's keys and
format them.my_dict = { 'id': [1, 'alice', 29], 'name': [2, 'bobbyhadz', 30], 'age': [3, 'carl', 31], } headers = list(my_dict.keys()) print( f'{headers[0].capitalize(): <10}{headers[1].capitalize(): <15}{headers[2].capitalize()}') # Id Name Age # 1 alice 29 # 2 bobbyhadz 30 # 3 carl 31 for _key, value in my_dict.items(): print(f'{value[0]: <10}{value[1]: <15}{value[2]}')
We used the dict.keys()
method to get a view of the dictionary's keys and used
an f-string to format the headers.
The dict.keys() method returns a new view of the dictionary's keys.
my_dict = {'id': 1, 'name': 'BobbyHadz'} print(my_dict.keys()) # ๐๏ธ dict_keys(['id', 'name'])
We also used the str.capitalize()
method to capitalize the first letter in
each key, but this is optional.
The str.capitalize() function returns a copy of the string with the first character capitalized and the rest lowercased.
print('bobby'.capitalize()) # ๐๏ธ 'Bobby' print('HADZ'.capitalize()) # ๐๏ธ 'Hadz'
You can also use the str.upper()
method if you need to convert each key to
uppercase.
You can also use the pandas module to print a dictionary in table format.
Make sure you have the module installed by running the following command.
pip install pandas # ๐๏ธ or with pip3 pip3 install pandas
Now you can import and use the pandas
module to create a DataFrame
from the
dictionary.
import pandas as pd my_dict = { 'Name': ['Alice', 'Bobby', 'Carl'], 'Age': [29, 30, 31] } df = pd.DataFrame(data=my_dict) # Name Age # 0 Alice 29 # 1 Bobby 30 # 2 Carl 31 print(df)
The DataFrame class is used to create two-dimensional tabular data.
Here is another example.
import pandas as pd my_dict = { 1: ['alice', 29], 2: ['bobbyhadz', 30], 3: ['carl', 31], } df = pd.DataFrame( [[key] + list(value) for key, value in my_dict.items()], columns=['ID', 'Name', 'Age'], ).set_index('ID') df = df.reset_index(drop=True) # Name Age # 0 Alice 29 # 1 Bobby 30 # 2 Carl 31 print(df)
The code sample explicitly sets the columns of the table.
I've also written an article on how to print specific key-value pairs in a dictionary.
You can learn more about the related topics by checking out the following tutorials: