How to use a dictionary to create an Anvil table?

Consider the following dictionary:

{“x” : [“a”, “b”]
“y” : [4, 7]
}

How can we use this dictionary to create a new table or populate an existing empty table?

The column names of that table would be the keys and each column would contain the values of the above dictionary.

How about the docs:-)?
Creating Data Grid via code
Adding the data or components to existing data grid

@KR1 In my post I am referring to the Anvil table (database) not Data grid.

1 Like

Ahh sorry.

you can populate the table with a list of rows.

list = [
{'column1key': value1, 'column2key': value2},
{'column1key': value3, 'column2key': value4}
]

right docs :slight_smile:

You can’t create a new table or database columns with a code. So you have to make it with provided UI and then load the data.

2 Likes

Thank you! That really helps.

You can actually create columns in existing Anvil table from code using anvil.tables.table_name.add_row method. It will add missing columns using value type to assign a type to a new column:

row_dict = {
    'column1': value1, 'column2': value2, 'column3': value3
}
anvil.table.my_table.add_row(**row_dict)

You have to switch this option on in app settings
Screenshot 2023-09-29 at 20.11.53

1 Like

Recommend switching it off afterwards. Otherwise, a bug in your code could end up adding unwanted columns.

1 Like