# Doing math between lists (dictionaries)

Hey guys, I had a great help from this forum before. I was trying to figure out this myself, but I decided to ask here since I didn’t have any progress in a few days.

I know how to make lists, but don’t know how to do a math between them:

``````            {% set ns = namespace(items=[]) %}
{% for med in states.sensor
| selectattr('entity_id', 'search', 'medication_')
| selectattr('attributes.time', 'defined') %}
{% set ns.items  = ns.items + [ {"name": med.attributes.pill_name, "average":med.attributes.usage/med.attributes.every }] %}
{%endfor%}
{{ ns.items }}

{% set ms = namespace(items=[]) %}
{% for med in states.input_number
| selectattr('entity_id', 'search', 'medication_')
%}
{% set ms.items  = ms.items + [ {"name":med.attributes.friendly_name, "count":med.state | float}] %}
{%endfor%}
{{ ms.items}}
``````

Output of ns.items:

``````[{'name': 'Burubus', 'average': 4.0}, {'name': 'Kurubus', 'average': 4.0}, {'name': 'Kurubus', 'average': 14.0}, {'name': 'Orbirus', 'average': 3.5}]
``````

Output of ms.items:

``````[{'name': 'Burubus', 'count': 74.0}, {'name': 'Kurubus', 'count': 95.0}, {'name': 'Orbirus', 'count': 70.0}]
``````

Now I should sum all ‘average’ for each ‘name’ it should look like this:

``````[{'name': 'Burubus', 'sum_average': 4.0}, {'name': 'Kurubus', 'sum_average': 18.0}, {'name': 'Orbirus', 'sum_average': 3.5}]
``````

And then list all names for ‘count’/‘sum_average’ < 10.

All of that should act as medication reminder for reordering. Pill name is unique for each medication, different sensors for different time schedules with specific “usage” (how many pills to take) “time” (when to take) and “every” (how often, for example every 2 days). Input_number is actually a counter and state is showing number of pills left. It should list pill names that I have to reorder if I have for only 10 days or less.

Also, if there is an easier approach please let me know

Cheers

Just do all the work in your second for loop.

``````            {% set ms = namespace(items=[]) %}
{% for med in states.input_number | selectattr('entity_id', 'search', 'medication_') %}
{% set name = med.attributes.friendly_name %}
{% set sum_average = ns.items | selectattr('name', 'eq', name) | map(attribute='average') | sum %}
{% set count = med.state | float %}
{% if count / sum_average < 10 %}
{% set ms.items  = ms.items + [ {"name": name, "count": count, "sum_average": sum_average}] %}
{% endif %}
{%endfor%}
``````
1 Like

Oh damn, that’s so smooth! Thank you a lot, it works like a charm! So elegant and powerful, amazing