How to translate jinja2 code from template editor to a script?

I developed some code in template editor and it works as expected. Now I would like to transfer the code to a script or translate to something equivalent but without success.
The script takes as input a PIN or TAG code from an input_text helper, looks for the corresponding username in an array and returns it in another input_text helper. Can someone guide me in the right direction?

{% set received_code = states('input_text.last_access_code') %}
{% set usercodes = [{'name':'User 1', 'pin':'1111', 'tag': '1111111'}, {'name':'User 2', 'pin':'2222', 'tag': '2222222'}, {'name':'User 3', 'pin':'3333', 'tag': '3333333'}, {'name':'User 4', 'pin':'4444', 'tag': '4444444'}] %}
{% set name = namespace(found='') %}
{% for item in usercodes if (received_code == item.pin) or (received_code == item.tag) %}
{% set name.found = item.name  %}
{% endfor %}
{{name.found}}

What have you tried that failed? If your Jinja2 code is working as you wish then getting that into a script or sensor is fairly straightforward. The question is which, since you are ending the code with a value, do you want that to be a sensor with the value as a state? Do you want a script that simply returns the value once calculated that you’ll then use in a different way?

Since you are using a return value, I’ll assume for demonstration that it is meant for a sensor:

template:
  - sensor:
      - name: "My Sensor"
        state: >-
          {% set received_code = states('input_text.last_access_code') %}
          {% set usercodes = [{'name':'User 1', 'pin':'1111', 'tag': '1111111'}, {'name':'User 2', 'pin':'2222', 'tag': '2222222'}, {'name':'User 3', 'pin':'3333', 'tag': '3333333'}, {'name':'User 4', 'pin':'4444', 'tag': '4444444'}] %}
          {% set name = namespace(found='') %}
          {% for item in usercodes if (received_code == item.pin) or (received_code == item.tag) %}
            {% set name.found = item.name  %}
          {% endfor %}
          {{name.found}}   

Works perfectly, it’s exactly what I needed. Thanks!

If two people have the same pin but different tags then the found value till over write

now, where can I move the array variable definition, to make it more accessible and in a more editable form? For example in a yaml file?