Ansible – Extract Key Tied to Minimum Value in Multiple Dictionaries

ansible

In my Ansible playbook I need to extract the name (i.e cory in this example),which has the lowest score (i.e 7).
How can I do it with the given list of dictionaries..?

[
        {
            "name": "james", 
            "score": "48"
        }, 
        {
            "name": "darcy", 
            "score": "37"
        },
        {
            "name": "cory", 
            "score": "7"
        }
 ]

Best Answer

Where is the data coming from? If you can make sure that your 'score' comes through as an int instead of a string this should be pretty easy.

- hosts: localhost
  gather_facts: no
  vars:
    data: [ { "name": "james", "score": 48 }, { "name": "darcy", "score": 37 }, { "name": "cory", "score": 7 } ]
  tasks:
  - debug:
      msg: "{{ (data |sort(attribute='score'))[0]['name'] }}"

# TASK [debug] *******
# ok: [localhost] => {
#     "msg": "cory"
# }