How to get the index of a trigger component

I’m building a Pattern-Matching Callbacks and I want to get the “index” number of the component that is triggered:

With dash.callback_context.triggered I get access to the followin information:

['{"index":4,"type":"filter-htmlP"}.n_clicks']

How can I get the number 4 (in this case)?

Thanks in advance :grinning:

1 Like

Hi @Eduardo

That’s a good question and I think it would be nice to have an example added to the docs :slight_smile:

Since dash.callback_context.triggered returns a string, there are lots of different ways to get the number. We could start a debate on which of these methods is the most Pythonic: regex - How to extract numbers from a string in Python? - Stack Overflow

Here is my favorite way :

Given that the prop_id is a stringified dictionary with no white space – which is a JSON format, you can use the json module to convert it back into a normal python dictionary. See the json.loads() method - more info on that here: Python JSON

I use this method to get the chart number to delete in this example: Pattern call-backs regarding adding dynamic graphs - #4 by AnnMarieW

import json
...

input_id = dash.callback_context.triggered[0]["prop_id"].split(".")[0]
index_number = json.loads(input_id)["index"]

Does anyone else have a better solution?

3 Likes

Thanks Ann Marie,

That’s what I was searching for :star_struck:

I was trying to understand the Pattern-Matching documentation about dash.callback_context but without any success. :woozy_face:

1 Like