Dash_Table in Python: style_data_conditional loop between columns

I want to format some cells of my dash table: backgroundColor of values in column T1 to green if the value in column T1 is equal to the value of column P1 for each row.

It works fine with the following code:

            {
            'if': {
                'filter_query': '{T1}={P1},
                'column_id': 'T1'
            },
            'backgroundColor': 'green',
            'color': 'white'
           }

But I need to format in the same way columns T2, T3, …, T18 if they are equal to P2, P3, …, P18. I have tried:

            {
            'if': {
                'filter_query': "'{T"+str(x)+"}={P"+str(x)+"}'",
                'column_id': "'T"+str(x)+"'"
            },
            'backgroundColor': 'green',
            'color': 'white'
            } for x in range(1, 19)

when I run my code, there is no error displayed but the cells are not formatted at all.

Any ideas of what I’m doing wrong? Thanks for any help.

I have tried several ways to concatenate without success.

Hi @JoseCorreia and welcome to the Dash community :slightly_smiling_face:

Try making it look like this:

style_data_conditional=(
    [
        {
            'if': {
                'filter_query': f'{{T{i}}} = {{P{i}}}',
                'column_id': f'T{i}',
            },
            'backgroundColor': 'green',
            'color': 'white'
        }
        for i in range(1,19)
    ]
)

you can see more examples of adding the conditional formatting in a loop here: Conditional Formatting | Dash for Python Documentation | Plotly

Thanks Ann Marie,
It works fine.
I have also succeeded this way:

          [           
            {
            'if': {
                'filter_query': '{T'+str(x)+'}={P'+str(x)+'}',
                'column_id': 'T'+str(x)
            },
            'backgroundColor': 'green',
            'color': 'white'
            } for x in range(1, 19)       
          ]

but your way is much more elegant…

1 Like