Template or variable syntax similar to SQL 'Decode'

The short of my question is that I’m trying to translate a favorite_id into understandable english. If I were using sql, I’d do something like:


decode(favorite_id,
'FV:2/57', 'Alternative Hits Radio',
'FV:2/62', 'Classic Rock Radio',
'FV:2/77', 'Cocktail Hour',
'FV:2/91', 'Cool Jazz',
'Unknown favorite')

So, what’s the most efficient way to do this in Home Assistant? I could do if, elif, elif, elif etc but that just seems really inefficient so I figured I’d reach out for help first before I waste time doing that.

For slightly more context, in case it’s helpful- I have an automation that when I press a button, a random favorite is chosen and then played on my Sonos speakers. I’m changing this to now select that random station as a variable and then announce what favorite was chosen on the speaker before actually playing the music. I have it all working, except I’d like to announce the station in understandable terms (‘Now Playing Cool Jazz’) rather than the favorite id that is the variable (‘Now Playing FV:2/91’) for example.

{% set id = {
'FV:2/57': 'Alternative Hits Radio',
'FV:2/62': 'Classic Rock Radio',
'FV:2/77': 'Cocktail Hour',
'FV:2/91': 'Cool Jazz'} %}

{{ id.get(favorite_id, 'Unknown favorite')}}
1 Like

thanks, that worked perfectly, but it brings up another potential question… When I look up the sensor.sonos_favorites attribute for what favorite IDs translate to which favorites, I see it’s in an incredibly similar format- is it possible to call this in some way when getting the favorite name so that it would always be up to date and wouldn’t rely on me updating the script if I add a new favorite?

If the dictionary already exists in an attribute you do not need to rebuild it… just call the get method on the results.

{{ (state_attr('sensor.sonos_favorites', 'items')).get(favorite_id, 'Unknown favorite') }}

yep, that did it. Much simpler than rebuilding and maintaining it myself. Thanks so much for your help. My initial googling of ‘home assistant template like sql decode’ was very much not helpful as you might imagine. You’ve been a huge help, thanks again.