How to Create a Table in Python
You can create a table in Python with a pandas DataFrame, a list of dictionaries, a SQLite database table, or formatted text printed in a loop. The right choice depends on whether you need to analyze data, store it permanently, look up values quickly, or simply display rows in a terminal. This guide starts with the most useful default, pandas, and then covers the common alternatives.
What a Table Means in Python
Python does not have one built-in object named table. Instead, a table is usually represented by a structure containing rows and columns:
- A pandas DataFrame is best for spreadsheets, CSV files, analysis, filtering, and reporting.
- A list of dictionaries is a simple built-in representation for small datasets.
- A list of tuples works well when every row has values in the same fixed order.
- A SQLite table stores data in a local database that you can query with SQL.
- A dictionary is Python’s usual hash table: it maps unique keys to values.
- A nested loop can produce a table-shaped report in the terminal, but it does not store the data unless you save it separately.
For most data tasks, create a DataFrame first; use another structure when storage, lookup speed, or simple output is the real goal.
How to Create a Table With pandas
Use this method when you want labeled columns, easy filtering and sorting, file import/export, or calculations across rows.
Choose the representation that matches what you need before writing the first row.
| Goal | Best Choice | Why |
|---|---|---|
| Analyze, filter, sort, or export tabular data | pandas DataFrame | Rows and columns have labels and built-in data operations |
| Keep a small table without extra packages | List of dictionaries | Uses only Python built-ins |
| Print a report in the terminal | Loops and formatted strings | Controls spacing and layout |
| Store data between program runs | SQLite | Supports SQL queries and persistent files |
| Find a record by a unique key | Dictionary | Provides hash-table-style key lookup |
| Refresh data continuously | A table platform such as Deephaven | Supports static and updating tables |
Step 1: Define the Columns and Rows
- Decide what each column means before adding data.
- Use one dictionary per row. Each dictionary key becomes a column name.
records = [
{"name": "Ava", "team": "Platform", "status": "active"},
{"name": "Noah", "team": "Data", "status": "active"},
{"name": "Mia", "team": "Support", "status": "pending"},
]
Each item in records is a row. The keys, name, team, and status, are the columns.
Keeping the column names consistent matters. If one row uses "team" and another uses "department", pandas will create separate columns rather than treating them as the same field.
Step 2: Build the DataFrame
- Install pandas with pip before creating the DataFrame:
python -m pip install pandas
- Import pandas, then pass records to DataFrame() to create the labeled table:
import pandas as pd
df = pd.DataFrame(
records,
columns=["name", "team", "status"],
)
print(df)
The columns= argument fixes the column order and makes the intended table layout explicit. A DataFrame can contain text, numbers, dates, missing values, and other Python objects, although a column is easiest to work with when its values have a consistent type.
Step 3: Check and Save the Finished Table
- Confirm that the DataFrame has the columns you intended.
- Print it or export it to a CSV file.
expected_columns = ["name", "team", "status"]
assert df.columns.tolist() == expected_columns
assert not df.empty
print(df)
df.to_csv("team-status.csv", index=False)
index=False prevents pandas from adding its internal row index as an extra CSV column. At this point, team-status.csv is a finished, portable table that can be opened in a spreadsheet program or read by another Python script.
Create a Table With Built-In Python Types
You do not need pandas for every table. For a small dataset used only inside your program, a list of dictionaries is often enough.
employees = [
{"name": "Ava", "role": "Developer"},
{"name": "Noah", "role": "Analyst"},
{"name": "Mia", "role": "Designer"},
]
for employee in employees:
print(employee["name"], employee["role"])
This is easy to read because each value has a named key. Add a row with append():
employees.append(
{"name": "Leo", "role": "Writer"}
)
You can also separate headers from rows by using tuples:
columns = ("name", "role")
rows = [
("Ava", "Developer"),
("Noah", "Analyst"),
("Mia", "Designer"),
]
This form is compact, but positions matter: the first value in every row belongs to name, and the second belongs to role. Dictionaries are usually safer when the table may grow or be edited later.
A Python list is an ordered, mutable collection. It can hold rows, strings, numbers, or mixed objects, which is why lists are commonly used as the outer container for small tables.
Print a Table With a Python Loop
Use loops when your goal is terminal output. A multiplication table is a useful example because it shows how nested loops create rows and cells.
for number in range(1, 11):
for product in range(number, number * 11, number):
print(f"{product:>4d}", end="")
print()
The outer loop, range(1, 11), starts each row from 1 through 10. The inner loop, range(number, number * 11, number), generates the multiples for the current row.
The format specifier :>4d right-aligns each integer in a field that is 4 characters wide, which keeps the columns lined up. end="" stops print() from starting a new line after each cell; the final print() starts the next row after the current row is complete.
Remember that range() stops before its ending value. To loop from 0 through 10, use range(11):
for index in range(11):
print(index)
This is a common source of missing final rows in loop-built tables.
For a table stored in a list of dictionaries, you can print selected fields with a loop:
for employee in employees:
print(f'{employee["name"]:<12} {employee["role"]}')
This creates readable output, but it does not give you DataFrame operations or database queries.
Create a SQL Table With SQLite
Use SQLite when the table must survive after the script exits or when you want to query it with SQL. Python includes the sqlite3 module, so this approach does not require a separate database server.
import sqlite3
with sqlite3.connect("projects.db") as connection:
connection.execute(
"""
CREATE TABLE IF NOT EXISTS projects (
name TEXT PRIMARY KEY,
owner TEXT NOT NULL,
status TEXT NOT NULL
)
"""
)
connection.execute(
"""
INSERT OR REPLACE INTO projects (name, owner, status)
VALUES (?, ?, ?)
""",
("Website", "Ava", "active"),
)
connection.commit()
result = connection.execute(
"SELECT name, owner, status FROM projects"
)
print(result.fetchall())
This script creates a projects.db file, creates the projects table if needed, inserts a row, and reads the row back to confirm it worked.
Use ? placeholders rather than building SQL strings with Python values. Placeholders keep the SQL structure separate from the data, handle quoting correctly, and avoid SQL injection risks when values come from users or external files.
Create a Hash Table With a Python Dictionary
A hash table is a key-value structure optimized for finding a value from a unique key. In Python, the built-in dict type is the normal hash-table implementation.
You can turn rows into a lookup table keyed by name:
by_name = {
row["name"]: row
for row in records
}
print(by_name["Ava"])
The result is a dictionary where "Ava" points to Ava’s complete row. This is useful when your program repeatedly needs one record by identifier.
Dictionary keys must be unique. If two rows use the same key, the later row replaces the earlier one:
by_name["Ava"] = {
"name": "Ava",
"team": "Platform",
"status": "inactive",
}
Use a dictionary for fast lookup, not as a replacement for a relational database. It does not support SQL queries, relationships, or persistent storage unless you write it to a file yourself.
Create Static and Updating Tables in Deephaven
A specialized table platform is useful when data changes continuously and you need the table to update as new values arrive. In Deephaven’s function-generated table API, a Python function returns a table and can run again when a timer refreshes or a source table updates.
Create a Static Deephaven Table
In Deephaven, empty_table(5) creates a starting table with 5 rows before you add columns. The following table adds a column of random integers and a column of random decimal values:
from deephaven import empty_table
table = empty_table(5).update([
"X = randomInt(0, 10)",
"Y = randomDouble(-50.0, 50.0)",
])
The expressions "X = randomInt(0, 10)" and "Y = randomDouble(-50.0, 50.0)" are Deephaven column expressions, not standard Python assignments. Inspect table in the Deephaven environment to view the completed result.
Refresh a Function-Generated Table
A function-generated Deephaven table must return a table with a stable set of column names and types. This example runs the generator when it is created and refreshes it every 60,000 milliseconds:
from deephaven import empty_table, function_generated_table
def make_table():
return empty_table(5).update([
"X = randomInt(0, 10)",
"Y = randomDouble(-50.0, 50.0)",
])
result = function_generated_table(
table_generator=make_table,
refresh_interval_ms=60_000,
copy_data=True,
)
For Deephaven function-generated tables, copy_data=True copies generated rows into the result table’s own column sources. The refresh_interval_ms=60_000 setting is appropriate for the documented weather-refresh pattern and means the function runs once per minute.
You can also trigger updates from a ticking source table. In Deephaven, time_table("PT1S") creates a time table with a one-second ISO 8601 period:
from deephaven import time_table
tt = time_table("PT1S")
A generator can list tt as a source table so that it runs when the trigger ticks. If a generated table fetches weather data or another HTTP resource, use timeout=10 on the request to bound the wait to 10 seconds. A generator can return None when it needs to keep the previous table result rather than replace it with incomplete data.
Check That Your Python Table Is Usable
- Keep a consistent type within each column where possible.
- Query a SQLite table after inserting data to confirm that the row was committed.
- Use unique dictionary keys when building a hash table.
For file-based workflows, export a DataFrame to CSV and read it again in a separate run. That verifies both the data layout and the saved file path.
Frequently Asked Questions
Do I Need pandas to Create a Table in Python?
No. A list of dictionaries or tuples can represent a small table inside a program, while SQLite stores a table that survives after the script exits. pandas is the best default when you need labeled columns, analysis tools, CSV support, filtering, sorting, and spreadsheet-like operations.
How Do I Define a Table in Python?
Define a table by choosing a row structure and then collecting rows in a container. A list of dictionaries is a clear option because each dictionary represents one row and each key represents a column name.
table = [
{"product": "Notebook", "category": "Office"},
{"product": "Headphones", "category": "Electronics"},
]
What Is a List in Python?
A list is an ordered, mutable collection written with square brackets. For tables, a list commonly holds rows, while each row is represented as a dictionary or tuple.
rows = [
("Ava", "Developer"),
("Noah", "Analyst"),
]
How Do I Create a Hash Table in Python?
Create a hash table with a dictionary using {} or dict(). Each key should be unique, and each key maps to one value or record.
users = {
"ava": {"role": "Developer"},
"noah": {"role": "Analyst"},
}
Use users["ava"] to retrieve Ava’s record.
Can a Python Loop Create a Data Table Instead of Just Printing One?
Yes. A loop can build a list by appending one row at a time, then you can pass that list to pandas or process it directly. Use a nested loop only when you need to generate combinations, such as rows and columns in a multiplication table; start with a list or DataFrame when the result needs to remain available after printing.
What Python code can create a simple table?
Use pandas by passing a dictionary of column data to pd.DataFrame(). After importing pandas as pd, create a dictionary such as d and run df = pd.DataFrame(data=d); its entries provide the columns and their values.
How do you create and view a table in a Jupyter Notebook?
Create a pandas DataFrame, then run a notebook cell containing only df to display the table. Jupyter shows a displayed DataFrame as an HTML table, while a plain-text terminal uses a text display.
How can you make a multiplication table in Python without tabulate?
Use nested for loops and formatted output to print the multiplication table. Set the outer loop to range(1, 11), then use range(number, number * 11, number) for each row’s multiples. Format each product with :>4d to keep the output columns aligned.
