Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

dash Dropdown provides either string or list depending on number of selections

I'm currently working on a stock analysis tool utilizing dash. I have a dropdown populated with the NASDAQ 100 symbols and am attempting to get it to return a line graph with a line for each symbol selected.

With the dropdown, if I have one symbol selected the returned value is a string, if I select multiple it's then a list.

I'm trying to use a callback such as:

@app.callback(
    Output(component_id='stock-graph-line', component_property='figure'),
    Input(component_id='stock-input', component_property='value'),
    suppress_callback_exceptions = True
)
def update_stock_symbol(input_value):
    for i in input_value:
        fig.append_trace({'x':df.index,'y':df[([i], 'close')], 'type':'scatter','name':'Price [Close]'},1,1)   

    fig['layout'].update(height=1000, title=input_value, template="plotly_dark")
    return fig

However, the for loop does not work with only one symbol selected as it's getting a string, not a list. Is there an option in dash to specify the return type of the callbacks? (Can I force it to pass on the one symbol as a list item?) Or does this have to be handled with if statements testing the type?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I set up a dropdown and it is always returning either None or a list:

dcc.Dropdown(
        id='dropdown-id',
        options=[
            {'label': 'a', 'value': 'a'},
            {'label': 'b', 'value': 'b'},
            {'label': 'c', 'value': 'c'},
            {'label': 'd', 'value': 'd'},
            {'label': 'e', 'value': 'e'},
        ],
        multi=True
    ),

Perhaps yours is set up differently. If that won't work, then just check like this:

def update_stock_symbol(input_value):
    if isinstance(input_value, str):
        input_value = [input_value]
    for i in input_value:
        ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...