Define columns in DataTable with "if .. else"

Hi,
Can I use condition “if … elif … else” when defining columns during create DataTable?
When I use " If … else " then working but when I add “elif” I have an error.

    dash_table.DataTable(
        id='our-table',
        columns=[{
                     'name': str(x),
                     'id': str(x),
                     'deletable': False,
                     "type": "date"
                 } if x == 'A' or x == 'B' or x == 'C'
            #      elif x == 'D' {
            # 'name': str(x),
            # 'id': str(x),
            # 'deletable': True,
            # "type": "numeric"
            #       }
                 else {
            'name': str(x),
            'id': str(x),
            'deletable': True,
            "type": "text"
        }
                 for x in df.columns],

Which python version are u using?

There is a match/case feature in the 3.10 easier and cleaner to implement.

Hello @lookasz,

Welcome to the community! You cant do what you are trying, even with just regular python.

What you can do is this:

x if x == 'A'... else (x if x == 'D' else x) for x in data

Here it is mapped out:

from dash import Dash, dash_table
import pandas as pd

app = Dash(__name__)

df = pd.DataFrame({
    i: [x for x in range(0,10)] for i in ['A', 'B', 'C', 'D', 'E']
})

tbl = dash_table.DataTable(
    id='our-table',
    data=df.to_dict('records'),
    columns=[{
             'name': str(x),
             'id': str(x),
             'deletable': False,
             "type": "datetime"
         } if x in ['A','B','C']
         else (
                {
                    'name': str(x),
                    'id': str(x),
                    'deletable': True,
                    "type": "numeric"
                }
                if x == 'D'
                else {
                    'name': str(x),
                    'id': str(x),
                    'deletable': True,
                    "type": "text"
                }
            )
         for x in df.columns],
    editable=True)

app.layout = tbl

app.run(debug=True)


2 Likes