Py.Cafe

maartenbreddels/

country-city-selector-dash

Country and City Picker

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import dash
from dash import dcc, html
from dash.dependencies import Input, Output, State

# Sample data for countries and cities
country_city_data = {
    "USA": ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"],
    "Canada": ["Toronto", "Vancouver", "Montreal", "Calgary", "Ottawa"],
    "Australia": ["Sydney", "Melbourne", "Brisbane", "Perth", "Adelaide"],
    "India": ["Mumbai", "Delhi", "Bangalore", "Hyderabad", "Chennai"],
    "UK": ["London", "Manchester", "Birmingham", "Leeds", "Glasgow"]
}

# Initialize the Dash app
app = dash.Dash(__name__)

# Layout of the app
app.layout = html.Div([
    html.H1("Country and City Picker"),
    dcc.Dropdown(
        id='country-dropdown',
        options=[{'label': country, 'value': country} for country in country_city_data.keys()],
        placeholder="Select a country",
        value=''
    ),
    dcc.Dropdown(
        id='city-dropdown',
        options=[],
        placeholder="Select a city",
        value=''
    ),
    html.Div(id='output-div'),
    html.Button('Reset', id='reset-button', n_clicks=0),
])

# Callback to update city dropdown based on selected country
@app.callback(
    Output('city-dropdown', 'options', allow_duplicate=True),
    Output('city-dropdown', 'value', allow_duplicate=True),
    Input('country-dropdown', 'value'),
    prevent_initial_call=True
)
def update_city_dropdown(selected_country):
    print("update_city_dropdown")
    if selected_country:
        cities = [{'label': city, 'value': city} for city in country_city_data[selected_country]]
        return cities, ''
    return [], ''

# Callback to display selected country and city
@app.callback(
    Output('output-div', 'children'),
    Input('country-dropdown', 'value'),
    Input('city-dropdown', 'value')
)
def display_selected_values(selected_country, selected_city):
    print("display_selected_values")
    if selected_country and selected_city:
        return [html.P(f"Selected Country: {selected_country}"), html.P(f"Selected City: {selected_city}")]
    return []

# Callback to reset the dropdowns
@app.callback(
    Output('country-dropdown', 'value', allow_duplicate=True),
    Output('city-dropdown', 'options', allow_duplicate=True),
    Output('city-dropdown', 'value', allow_duplicate=True),
    Input('reset-button', 'n_clicks'),
    prevent_initial_call=True
)
def reset_dropdowns(n_clicks):
    print("Button")
    if n_clicks > 0:
        return '', [], ''
    return dash.no_update, dash.no_update, dash.no_update

# Run the app
if __name__ == '__main__':
    app.run_server(debug=True)