Get value of key-value array through variable

Perhaps a silly question, but I’m unable to find the answer…

This is my current code (that does NOT work):

{% set mqttTopicsMap = { 'humidifier' : 'home/Bedroom/Humidifier/cmnd/teleperiod',
                         'bathroom' : 'home/Bathroom/Bathroom/cmnd/teleperiod',
                         'chrismastree' : 'home/Livingroom/ChristmasTree/cmnd/teleperiod',
                         'spareplug' : 'home/unassigned/Spare-Plug/cmnd/teleperiod'} %}
{% set targetSwitch = (states('input_select.tasmota_switch') | lower).replace(' ', '').replace('-','') %}
   
{{ mqttTopicsMap[targetSwitch] }}

Although my targetSwitch is properly read and parsed, I seem to be unable to pass it as a value for an array.

My aim is to abstract the MQTT topic and have an input_select to select apropriate switch.
Through some “submit”-button (still need to figure out that one), it will launch a script to publish a specific MQTT payload to the to corresponding switch topic.
(Final objective: have a very simple “configuration” screen in lovelace to manage some MQTT and other config parameters)

Hi, @tstas:

I copied your code into the developer/template editor to test it. I first set the input_select to humidifier. Then changed the input_select to bathroom. In both cases, it worked as the key for the dictionary by producing the matching value from the dictionary.

The screen shots from the bathroom selection are:


image

Note that I also printed the value of targetSwitch in the template editor. I’m thinking your options in the input_select are a little more sophisticated than the keys that you are checking for (the replace commands made me think that). Have you inspected these in the template editor to make sure they are what you think they are? And can you show how the input_select.tasmota_switch is defined? Here’s how I defined it for testing:

input_select:
  tasmota_switch:
    options:
      - humidifier
      - bathroom
      - chrismastree
      - spareplug

Last question - I’m assuming this is a template for something - can you provide the full context? Automation, template sensor, etc. That will help figure out what’s not working as you expect.

1 Like

In addition to the excellent previous post, is chrismastree a typo, shouldn’t it be christmastree

1 Like

I wondered about that, too! And thank you for the compliment!!

Fixed indeed due to type… my bad…

Case closed :wink:

1 Like