Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple dependent widgets (dropdown menu) on Jupyter notebook

I was following the example on how to handle multiple dependent widgets on jupyter notebooks from here:

Dynamically changing dropdowns in IPython notebook widgets and Spyre

In that example the code solution was the following:

from IPython.html import widgets
from IPython.display import display

geo={'USA':['CHI','NYC'],'Russia':['MOW','LED']}

def print_city(city):
    print city

def select_city(country):
    cityW.options = geo[country]


scW = widgets.Dropdown(options=geo.keys())
init = scW.value
cityW = widgets.Dropdown(options=geo[init])
j = widgets.interactive(print_city, city=cityW)
i = widgets.interactive(select_city, country=scW)
display(i)
display(j)

so, the second dropdown is dependent on the value of the first one. Here the question: What if i want to create a third dropdown that is dependent on the value of the second one? Let's say that each of the cities above (CHI, NYC, MOW, LED) have some districts, and I'd like a third dropdown that change every time that a city is updated.

Hope that the problem is clear, thank you!

like image 750
davidvarenne Avatar asked Oct 21 '25 17:10

davidvarenne


1 Answers

Just in case you never found a solution: I have one here that works in python 3. I've commented everything that I changed from the original code. I hope it helps!

from IPython.html import widgets
from IPython.display import display

geo={'USA':['CHI','NYC'],'Russia':['MOW','LED']}

geo2={'CHI':['1','2'],'NYC':['3','4'],'MOW':['5','6'],'LED':['7','8']} #create dictionary with city districts

def print_city(city,district):
    print(city)
    print(district) #add in command to print district

def select_city(country):
    cityW.options = geo[country]

#add in 'select district' function that looks in the new dictionary
def select_district(city):
    districtW.options = geo2[city]

scW = widgets.Dropdown(options=geo.keys())
init = scW.value
cityW = widgets.Dropdown(options=geo[init])


init2= cityW.value #new start value for district dropdown
districtW = widgets.Dropdown(options=geo2[init2]) #define district dropdown widget

j = widgets.interactive(print_city, city=cityW, district=districtW) #define district value
i = widgets.interactive(select_city, country=scW)

k = widgets.interactive(select_district, city=cityW) #call everything together with new interactive

display(i)
display(j)
like image 60
AaylaSecura Avatar answered Oct 24 '25 06:10

AaylaSecura



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!