6

Is it possible to get the value of a specific cell when using prettytable?

I have the following code to iterate through all rows of a simple table.

from prettytable import PrettyTable

table = PrettyTable(["Column 1", "Column 2", "Column 3"])
table.add_row(["A", "B", "C"])
table.add_row(["F", "O", "O"])
table.add_row(["B", "A", "R"])

for row in table:
    print(row)

This example prints the following 3 tables:

+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
|    A     |    B     |    C     |
+----------+----------+----------+
+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
|    F     |    O     |    O     |
+----------+----------+----------+
+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
|    B     |    A     |    R     |
+----------+----------+----------+

How is it possible to get only the value of Column 1, Column 2 or Column 3 of a row?

2
  • Please see the following link. Commented Jun 23, 2014 at 12:19
  • This gives me a subset of the table. But how can I get the values of the cells of the defined subset? For example I want to get A or B. Commented Jun 23, 2014 at 12:27

3 Answers 3

8

It looks like what you want to do is get a subset of the data, from the documentation here, try:

from prettytable import PrettyTable

table = PrettyTable(["Column 1", "Column 2", "Column 3"])
table.add_row(["A", "B", "C"])
table.add_row(["F", "O", "O"])
table.add_row(["B", "A", "R"])

for row in table:
    print row.get_string(fields=["Column 1"]) # Column 1

Edit: It looks like you don't want the headers or border, just the value, in which case, this should work:

from prettytable import PrettyTable

table = PrettyTable(["Column 1", "Column 2", "Column 3"])
table.add_row(["A", "B", "C"])
table.add_row(["F", "O", "O"])
table.add_row(["B", "A", "R"])

for row in table:
    row.border = False
    row.header = False
    print row.get_string(fields=["Column 1"]).strip() # Column 1
0
0

In newer version of the prettytable you have the json/svc get:

In [13]: json.loads(table.get_json_string())[1]['Column 1']
Out[13]: 'A'

OR

In [17]: table.get_csv_string(header=False).split(',')[0]
Out[17]: 'A'

In the older version

In [28]: table[-1].get_string(header=False, fields=['Column 1']).split('|')[1].strip()
Out[28]: 'A'
-1

You have the rows method to get access to the raw data

table.rows[0][0]   # ="A"
1
  • There is no rows method in my PrettyTable from prettytable import PrettyTable; table = PrettyTable(["Column 1", "Column 2", "Column 3"]); type(getattr(table, 'rows', None)) # Out[3]: NoneType
    – vr286
    Commented Jul 8, 2022 at 9:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.