Dropdown options, pass a variable

Hi, I am try to pass a variable into options dropdown attribute so I can load any variable I want in it.
Let’s say I want to use a file to create a list of options like this :

def get_countries():
    """Load all countries from a file"""
    countries = []
    with open('./data/countries.txt', 'r', encoding='utf-8') as countries_file:
        for country in countries_file:
            country_data = country.split('|')
                    'label': country_data[0],
                    'value': country_data[1].strip('\n')
    return countries

Assuming the file look like somthing like this :


I put the return value of my function get_countries in a variable countries :

But when I try to put it in the dropdown attribute :


I get the error :

Invalid argument options[0] passed into Dropdown with ID “country”.
Expected object.
Was supplied type array.

I would like to know if it is possible, and if it is : how to proceed. I tried to get the object Options from html.Option(), but it doesn’t work.

Thank you for your help.

Hi @thibaultmagy and welcome to the Dash community!

Assuming that your function works correctly and if you print(countries) right before the return, you get something that looks like:
[{‘label’: ‘AF’, ‘value’: ‘Afghanistan’}, {‘label’:‘AL’, ‘value’: ‘Albania’}, … etc]

Instead of: options=[countries],

Try: options=get_countries(),

1 Like

Hi thank you for your answer, it works.

The return looked exactly like this.

Thank you again.

1 Like