print(tabulate(data))
---- ----------- ---------
42 forty-two foo & bar
99 ninety-nine
7 seven baz
-113 xyz etc.
---- ----------- ---------
Adding a header:
print(tabulate(data, headers = ['Num', 'Text', 'Other']))
Num Text Other
----- ----------- ---------
42 forty-two foo & bar
99 ninety-nine
7 seven baz
-113 xyz etc.
Specify the columns' alignment:
print(tabulate(data, headers = ['Num', 'Text', 'Other'], colalign=('left', 'center', 'right')))
Num Text Other
----- ----------- ---------
42 forty-two foo & bar
99 ninety-nine
7 seven baz
-113 xyz etc.
Render the result of an SQL statement in a Jupyter Notebook
tablefmt = 'html' formats the data as HTML. This is especially useful when being used in a Jupyter Notebook.
The following example uses the cx_Oracle library to execute an SQL statement on an Oracle database and render the result in an HTML table:
import cx_Oracle as cxora
import tabulate
con = cxora.connect(user='rene', password = 'theSecret' dsn='ora19')
cur = con.cursor()
res = cur.execute('''
select
object_name,
object_type,
status,
created,
object_id
from
user_objects'''
).fetchall()
tabulate.tabulate(res, tablefmt = 'html', headers = [ _[0] for _ in cur.description ])
Displaying the result of a Wikidata SPARQL query
The following example uses the Python library requests to query the Wikidata endpoint and then displays the result in tabular form using the tabulate library (see also this requests example).
import requests
from tabulate import tabulate
query = """
select
(lang(?label) as ?lang)
?label
{
wd:Q22661317 rdfs:label ?label .
}
"""
response = requests.get(
'https://query.wikidata.org/sparql' ,
params = {'query' : query },
headers = {'Accept': 'application/sparql-results+json'}
)
response_json = response.json()
results = response_json['results']['bindings']
#
# List of tuples containing the data for each row in the table
#
table_data = [
(
result['lang' ]['value'],
result['label']['value']
)
for result in results]
print(tabulate(table_data, headers = ['Item', 'Label']))