Accessing currently selected keys of a MultiSelect widget with dict options

With a MultiSelect widget created from a dictionary is there a way to get the currently selected keys?

For example, if I create the widget:

ms = pn.widgets.MultiSelect(
    options={'mamals':['cat', 'dog'], 'birds': ['raven', 'jay']}
)

and then select mammals

image

Is it possible to get mammals back as the currently selected key from ms?

I’m not seeing the keys as a parameter anywhere. Obviously, this is accessible internally somewhere. I can implement a way to do what I want with the current values instead of the keys, but at this point I’m curious about how this is working.

Maybe this is possible with a function that watches the multiselect?

Thanks!

Hi @bt-1

Analysis - Minimum Reproducible Example

import panel as pn

pn.extension(design="material")

ms = pn.widgets.MultiSelect(
    options={'mamals':['cat', 'dog'], 'birds': ['raven', 'jay']}
)

def write(value):
    return str(value)

pn.Column(
    ms, pn.bind(write, ms.param.value)
).servable()

image

Solution - Just use the list of the keys as options

Its often easier to let the widget use a list of keys as options instead of the dictionary of keys and values. You can always extract the values from the keys.

import panel as pn

pn.extension(design="material")

options = {'mamals':['cat', 'dog'], 'birds': ['raven', 'jay']}

ms = pn.widgets.MultiSelect(
    options=list(options)
)

def write(value):
    return str(value)

def write_lists(value):
    selection = [options[key] for key in value]
    return str(selection)

pn.Column(
    ms, pn.bind(write, ms.param.value), pn.bind(write_lists, ms.param.value)
).servable()

image

Comment

I’ve looked through the implementation of the MultiSelect and its parent classes and I don’t see the value being stored in an attribute or parameter.

@Marc, thanks for the reply; I’ll keep this in mind in the future when using MultiSelect widgets. I didn’t see the value in attribute or parameter either. I’m still curious how the widget internally knows which keys are selected and updates the values.