Dicts in scripts

Can dicts be used in scripts? The following:

state = hass.states.get('sensor.next_waterloo_train_status')
train_status = state.state

mappings = {
'ON TIME':'green',
'LATE':'orange',
'CANCELLED':'red',
}


hass.services.call('light', 'turn_on', { "entity_id" : 'light.lamp',
                                         'color_name': mappings[train_status]
                                         })

Gives error:

Traceback (most recent call last):
  File "/usr/src/app/homeassistant/components/python_script.py", line 107, in execute
    exec(compiled.code, restricted_globals, local)
  File "hello_world.py", line 17, in <module>
NameError: name '_getitem_' is not defined

Hi i have the same problem … did you solve the problem ?

No solution I know of I’m afraid

Scripts support templating so try using the templating engine jinja - https://home-assistant.io/docs/configuration/templating/

{%- set myvar = {'dict': 'of', 'key': 'and', 'value': 'pairs'} -%}
{% print myvar['dict'] %}

That should print out ‘of’.

In your specific example you’d have to use templating instead of YAML for both the mappings and variable use.

3 Likes

I’ve discovered that lists are also not indexable.

hass.states.get(entities[0])
returns
NameError: name '_getitem_' is not defined

This has been fixed: https://github.com/home-assistant/home-assistant/pull/8541

1 Like