🧠 PYTHON TIP + DASH: Smart Filters with Dependent Dropdowns
📰 Edição #44 — PYTHON TIP + DASH: Smart Filters with Dependent Dropdowns
1. ✨ Opening Sentence
Have you ever imagined your dashboard guiding the user only through valid and logical paths? With dependent filters, that's entirely possible!
2. ✅ Tip Objective
Teach how to create dynamic and chained dropdowns using Dash, ensuring the options shown are always consistent with previous selections.
3. 📚 Technical Concept
Dependent dropdowns are filters whose available options change dynamically based on another filter's selection. This is achieved using callbacks that update layout components based on multiple Input and Output.
4. 💡 Python Representation
We use the Dash (Plotly) library to compose the web interface and reactive filters. Smart control is handled via callbacks between selectors.
5. 🧪 Python Script with Comments
import dash
from dash import dcc, html, Input, Output
import pandas as pd
import plotly.express as px
# ========================
# 🔢 SIMULATED DATA
# ========================
categories = {
'Electronics': ['Smartphone', 'Notebook', 'TV'],
'Furniture': ['Chair', 'Table', 'Cabinet'],
'Clothing': ['Shirt', 'Pants', 'Jacket']
}
stock_levels = {
'Smartphone': 25, 'Notebook': 12, 'TV': 7,
'Chair': 40, 'Table': 15, 'Cabinet': 9,
'Shirt': 100, 'Pants': 80, 'Jacket': 45
}
# ========================
# 🚀 DASH APP
# ========================
app = dash.Dash(__name__)
app.title = "Dependent Dropdowns with Stock Chart"
# ========================
# 🎨 LAYOUT
# ========================
app.layout = html.Div([
html.H2("Dependent Dropdowns with Stock Chart", style={"textAlign": "center"}),
html.Div([
html.Div([
html.Label("Category", style={'fontWeight': 'bold'}),
dcc.Dropdown(
id='dropdown-category',
options=[{'label': k, 'value': k} for k in categories],
value='Electronics',
clearable=False
)
], style={'flex': '1', 'marginRight': '20px'}),
html.Div([
html.Label("Model", style={'fontWeight': 'bold'}),
dcc.Dropdown(
id='dropdown-model',
clearable=False
)
], style={'flex': '1'})
], style={'display': 'flex', 'width': '60%', 'margin': '0 auto', 'padding': '40px 0'}),
html.Div([
dcc.Graph(id='stock-graph')
], style={'width': '50%', 'margin': '0 auto'})
])
# ========================
# CALLBACKS
# ========================
@app.callback(
Output('dropdown-model', 'options'),
Output('dropdown-model', 'value'),
Input('dropdown-category', 'value')
)
def update_model_dropdown(category):
models = categories.get(category, [])
options = [{'label': m, 'value': m} for m in models]
default_value = models[0] if models else None
print(f"[DEBUG] Category: {category} → Models: {models}")
return options, default_value
@app.callback(
Output('stock-graph', 'figure'),
Input('dropdown-model', 'value')
)
def update_stock_chart(model):
if not model or model not in stock_levels:
return px.bar(title="Select a valid model")
# Create DataFrame for compatibility with px.bar
df = pd.DataFrame({'Model': [model], 'Stock': [stock_levels[model]]})
fig = px.bar(
df,
x='Model',
y='Stock',
text='Stock',
title=f"Stock Level for: {model}",
labels={'Stock': 'Units in Stock'}
)
fig.update_traces(textposition='outside')
fig.update_layout(
yaxis=dict(range=[0, max(stock_levels.values()) * 1.1])
)
return fig
# ========================
# RUN
# ========================
if name == '__main__':
app.run(debug=True)
6. 🖼️ Generated Images
7. 📊 Script Explanation
This code creates a filter system that guides the user from Category to Model — always respecting the available data and selections already made.
8. 🛠️ Practical Applications
• Budget planning dashboards • Filters in CRM systems • Performance analysis by unit/category • Interactive BI reports
9. 🌐 Integration with Power BI
You can embed this Dash app directly into Power BI Service using an <iframe>:
Recommended by LinkedIn
<iframe src="https://your-dash-app.com" width="100%" height="600"></iframe>
10. 💼 Real-World Example
Imagine a budget dashboard: the user selects the fiscal year, then the business unit, and finally the cost center. Each step reduces errors and makes the experience intuitive.
11. 💬 EXTRA TIP
Want to make the dropdown even smarter? Add placeholder, set disabled=True until data loads, and use dash.no_update to avoid errors during callbacks.
12. 📅 CTA – Keep Exploring!
Want to turn your spreadsheets into smart visual tools? Explore more tips like this:
💼 LinkedIn & Newsletters:
💼 Company Page:
💻 GitHub:
13. 🔁 Filter Connectivity
Each dropdown acts as a sequential input — reducing invalid choices, improving user experience, and making the dashboard more reliable.
14. 🧠 Strategic Benefit
Dependent dropdowns enhance dashboard usability and drastically reduce filter conflicts or user mistakes.
15. 🏷️ Hashtags
#Python #Dash #DynamicDropdowns #SmartDashboards #PowerBI #DataVisualization #PythonForProductivity