How to Print Dictionaries in Table Format in Python
Representing dictionary data in a clear, tabular format enhances readability.
This guide explores various techniques for printing dictionaries as tables in Python. We'll cover manual formatting with f-strings, using the tabulate
library, and employing pandas
DataFrames for more structured output.
Printing Dictionaries in Table Format with f-strings
f-strings provide a flexible way to control output formatting.
Dictionaries with List Values
If each dictionary value is a list you can use that value to print each row in the table:
my_dict = {
1: ['alice', 29],
2: ['anna', 23],
3: ['carl', 31],
}
headers = ['ID', 'Name', 'Age']
print(f'{headers[0]:<10}{headers[1]:<15}{headers[2]}') # Print headers
for key, value in my_dict.items():
print(f'{key:<10}{value[0]:<15}{value[1]}') # Access list value by index
Output:
ID Name Age
1 alice 29
2 anna 23
3 carl 31
- The f-string formats each column using
<
for left alignment and a specified width.
Dictionaries without List Values
If the dictionary values are not lists, you can iterate through the key-value pairs directly:
my_dict = {
'id': 1,
'name': 'tomnolan',
'age': 25
}
for key, value in my_dict.items():
print(f'{key:<10}{value}')
Output:
id 1
name tomnolan
age 25
Dictionaries with Keys as Headers
To use dictionary keys as headers, use my_dict.keys()
method:
my_dict = {
'id': [1, 'alice', 29],
'name': [2, 'anna', 23],
'age': [3, 'carl', 31],
}
headers = list(my_dict.keys())
print(
f'{headers[0].capitalize():<10}{headers[1].capitalize():<15}{headers[2].capitalize()}')
for key, value in my_dict.items():
print(f'{value[0]:<10}{value[1]:<15}{value[2]}')
Output:
Id Name Age
1 alice 29
2 anna 23
3 carl 31
my_dict.keys()
provides access to the dictionary keys to be used as headers.capitalize()
formats the headers.
Printing Dictionaries as Tables with tabulate
The tabulate
library provides specialized table formatting. Install it using: pip install tabulate
.
from tabulate import tabulate
my_dict = {
'id': [1, 2, 3],
'name': ['Alice', 'Bob', 'Carl'],
'age': [25, 30, 28]
}
headers = ['ID', 'Name', 'Age']
data = list(zip(*my_dict.values())) # Transpose the values
print(tabulate(data, headers=headers, tablefmt='grid'))
Output:
+----+--------+-------+
| ID | Name | Age |
+====+========+=======+
| 1 | Alice | 25 |
+----+--------+-------+
| 2 | Bob | 30 |
+----+--------+-------+
| 3 | Carl | 28 |
+----+--------+-------+
- You transpose the dictionary’s values to form rows for the table.
- The
tablefmt
argument changes the style of the output.
Printing Dictionaries as Tables with pandas
The pandas
library excels at working with tabular data. Install it using: pip install pandas
import pandas as pd
my_dict = {
'Name': ['Alice', 'Anna', 'Carl'],
'Age': [29, 30, 31]
}
df = pd.DataFrame(data=my_dict)
print(df)
Output:
Name Age
0 Alice 29
1 Anna 30
2 Carl 31
my_dict2 = {
1: ['alice', 29],
2: ['tomnolan', 30],
3: ['carl', 31],
}
df2 = pd.DataFrame(
[[key] + list(value) for key, value in my_dict2.items()],
columns=['ID', 'Name', 'Age'],
).set_index('ID')
df2 = df2.reset_index(drop=True)
print(df2)
Output:
Name Age
0 alice 29
1 tomnolan 30
2 carl 31
- The
pandas.DataFrame
class allows you to print the dictionary as an easy-to-read table. set_index()
andreset_index()
methods are used to manipulate row indices.