Labels and Values in a selectbox with `format_funct`?

Hello! I have the following data

	display_name	          pbp_name	     abbr
0	Reggie Kelly	          R.Kelly	      ATL
1	Brandon Stokley	          B.Stokley       BAL
2	Charlie Batch	          C.Batch	      DET
3	Matt Hasselbeck	          M.Hasselbeck	  GB

I want to create a st.selectbox() that consists of options from the display_name column. Upon selecting a label, I would like to assign two variables, player and team.

For example, if a player selected Brandon Stokley from the selectbox, I would like streamlit to assign B.Stokley to the player variable and BAL to the team variable. I have realized you can do this with form_func, but I’m just not sure how. Should I transform this into a dictionary with multiple values like so

{'Brandon Stokley' : ['B.Stokley','BAL']}

And then use form_func as someone answered in this question with the below code?

CHOICES = {1: "dataset a", 2: "dataset b", 3: "dataset c"}

def format_func(option):
    return CHOICES[option]

option = st.selectbox("Select option", options=list(CHOICES.keys()), format_func=format_func)

Again, I would like for display_name to be the labels in my selectbox that will ultimately assign its corresponding pbp_name and abbr values to the variables player and team respectively.

Hey @bismo!

You can use to_dict(“records”) to transform dataframe into a list of dicts then use that list with selectbox something like this,

import streamlit as st
import pandas as pd

df = pd.DataFrame({"display_name": ["Reggi", "Kelly", "Brandon"], "pbp_name": ["R", "K", "B"], "abbr": ["RE", "KE", "BR"]})

records = df.to_dict("records")

selected_data = st.selectbox("Select from DF", options=records, format_func=lambda record: f'{record["display_name"]} - {record["pbp_name"]} - {record["abbr"]}')

Hope it helps! :slight_smile:

Cool @ash2shukla, is there a way I get the selectbox to just display display_name, so it would just be Reggie for example, instead of also including R - RE? And from the dictionary it returns, I can just assign the variables like so:

player = selected_data.get('pbp_name')

team = selected_data.get('abbr')

Correct? This should assign R to player and RE to abbr, no?

Thanks again!

1 Like

@bismo, you can change the format func to this to only show display_name

format_func=lambda record: f'{record["display_name"]}')

And yep you can just do that to get pbp_name and abbr :slight_smile:

1 Like