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?

Christian Berendt
  • 3,416
  • 2
  • 13
  • 22
  • Please see the [following link](https://code.google.com/p/prettytable/wiki/Tutorial#Selecting_subsets_of_data). – Cory Kramer Jun 23 '14 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`. – Christian Berendt Jun 23 '14 at 12:27

3 Answers3

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
Woodham
  • 4,053
  • 2
  • 20
  • 15
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'
vr286
  • 826
  • 7
  • 6
-1

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

table.rows[0][0]   # ="A"
Yanai Ankri
  • 439
  • 4
  • 11
  • 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 Jul 08 '22 at 09:50