Iterate over row columns

Hi, I’m trying to put together a “smart search” field that will look for a substring in each text column of a row.

How can I iterate over the columns of a row without specifying their names (or is there a command to get a list of all available columns and their types from the iterator)?

A row is essentially a Python dictionary (type dict). Standard dict iteration features should apply.

You can experiment with print() to get various “parts” of rows’ structure. You can iterate through column names like this (or invent something more pythonic :grinning:):

  rows = app_tables.some_table.search()
  for row in rows[0]:
    print(row[0])
1 Like

You can call app_tables.my_table.list_columns() to get a list of all the column names for a table. This doesn’t expose the types of these columns, but it does allow you to at least enumerate the columns efficiently :slight_smile:

(More info in the data tables API docs)

2 Likes

This post was very helpful! I could not find this in the reference docs, or in the tooltip/autocomplete prompt in the code view. (I’m not sure if it needs to be in either, but just thought I’d mention)

Also, this function appears to give a list of dicts, where each item of the list is a dict of (column data type, column name).

3 Likes

Adding to this old thread in case anyone else wanting to iterate over RowObject ended up here as I did. This was the only thread Google provide and the answers weren’t quite what I needed, but they were enough to point me in the right direction.

I wanted to use a row object in a dictionary comprehension. So something like:

my_copy = {k:v for k,v in self.item.items()}

where self.item was a <LiveObject: anvil.tables.Row>

Alas it cannot be done like that as an anvil.tables.Row doesn’t have a items method. Nor can you cheat with:

my_copy = {k:self.item[k] for k in self.item}

In this case the items returned are a tuple where element at index 0 is the column name, index 1 is the value.

So do actually achieve what I wanted the required code was:

my_copy = {k[0]:k[1] for k in self.item}

Since you’re trying to make a dict, you might try something like:

my_copy = dict(self.item)
1 Like

Thanks, I’ll keep that in mind if I need a full copy.
Using the dictionary comprehension allowed me to be picky about the things I copied. I didn’t include it in the example as I was giving a minimal example to illustrate.

1 Like