Create Python tabulate table from a Dictionary
In this tutorial, you’ll learn how to create formatted tables from dictionaries using the Python tabulate library.
You’ll explore various dictionary structures and how to convert them into tables.
Create a table from a dictionary
To create a simple table from a dictionary, you can use the tabulate function.
You can create a basic table from a dictionary using the tabulate function like this:
from tabulate import tabulate data = { "Name": "Amr", "Age": 28, "City": "Cairo", "Occupation": "Software Engineer" } table = tabulate(data.items(), headers=["Key", "Value"], tablefmt="grid") print(table)
Output:
+-------------+--------------------+ | Key | Value | +=============+====================+ | Name | Amr | +-------------+--------------------+ | Age | 28 | +-------------+--------------------+ | City | Cairo | +-------------+--------------------+ | Occupation | Software Engineer | +-------------+--------------------+
The code converts the dictionary items into a list of key-value pairs and creates a table with “Key” and “Value” headers.
Create a table from a Dictionary with list values
To create a table from a dictionary with list values, use the zip function to pair keys with their corresponding values:
from tabulate import tabulate data = { "Name": ["Fatma", "Hassan", "Nour"], "Age": [25, 32, 28], "City": ["Alexandria", "Giza", "Luxor"] } headers = list(data.keys()) values = list(zip(*data.values())) table = tabulate(values, headers=headers, tablefmt="pretty") print(table)
Output:
+--------+-----+------------+ | Name | Age | City | +--------+-----+------------+ | Fatma | 25 | Alexandria | | Hassan | 32 | Giza | | Nour | 28 | Luxor | +--------+-----+------------+
This code extracts the keys as headers and uses zip to create rows from the list values.
Create a table from a Dictionary of Dictionaries
To create a table from a nested dictionary, flatten the structure and use the keys as column headers:
from tabulate import tabulate data = { "Aisha": {"age": 30, "job": "Teacher", "city": "Aswan"}, "Karim": {"age": 28, "job": "Engineer", "city": "Port Said"}, "Laila": {"age": 35, "job": "Doctor", "city": "Hurghada"} } headers = ["Name"] + list(next(iter(data.values())).keys()) table_data = [[name] + list(info.values()) for name, info in data.items()] table = tabulate(table_data, headers=headers, tablefmt="pipe") print(table)
Output:
| Name | age | job | city | |:-------|------:|:----------|:----------| | Aisha | 30 | Teacher | Aswan | | Karim | 28 | Engineer | Port Said | | Laila | 35 | Doctor | Hurghada |
This code flattens the nested structure, using the outer keys as the “Name” column and the inner keys as additional columns.
Create a table from a Dictionary with hierarchical keys
To create a table from a dictionary with hierarchical keys, you can use a recursive function to flatten the structure:
from tabulate import tabulate def flatten_dict(d, parent_key='', sep='_'): items = [] for k, v in d.items(): new_key = f"{parent_key}{sep}{k}" if parent_key else k if isinstance(v, dict): items.extend(flatten_dict(v, new_key, sep=sep).items()) else: items.append((new_key, v)) return dict(items) data = { "Egypt": { "Cairo": {"population": 9700000, "area": 3085}, "Alexandria": {"population": 5200000, "area": 2679} }, "Sudan": { "Khartoum": {"population": 5274321, "area": 22142}, "Omdurman": {"population": 2395159, "area": 614} } } flattened_data = flatten_dict(data) headers = ["Country_City", "Statistic", "Value"] table_data = [[k.split('_')[0], k.split('_')[1], v] for k, v in flattened_data.items()] table = tabulate(table_data, headers=headers, tablefmt="fancy_grid") print(table)
Output:
╒════════════════╤═════════════╤═════════╕ │ Country_City │ Statistic │ Value │ ╞════════════════╪═════════════╪═════════╡ │ Egypt │ Cairo │ 9700000 │ ├────────────────┼─────────────┼─────────┤ │ Egypt │ Cairo │ 3085 │ ├────────────────┼─────────────┼─────────┤ │ Egypt │ Alexandria │ 5200000 │ ├────────────────┼─────────────┼─────────┤ │ Egypt │ Alexandria │ 2679 │ ├────────────────┼─────────────┼─────────┤ │ Sudan │ Khartoum │ 5274321 │ ├────────────────┼─────────────┼─────────┤ │ Sudan │ Khartoum │ 22142 │ ├────────────────┼─────────────┼─────────┤ │ Sudan │ Omdurman │ 2395159 │ ├────────────────┼─────────────┼─────────┤ │ Sudan │ Omdurman │ 614 │ ╘════════════════╧═════════════╧═════════╛
This code uses a recursive function to flatten the hierarchical dictionary.
It then creates a table with columns for the country, city, statistic type, and value.
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.