鱼鱼鱼三条鱼
鱼鱼鱼三条鱼

Reputation: 69

How to sort dict by value

I have a dict, that looks like:

{"dest_ip1":average_ping_time,"dest_ip2":average_ping_time,"dest_ip3:average_ping_time}

I want to sort it by value(average_ping_time), suppose average_ping_time of dest_ip2 is less than average_ping_time of dest_ip1 and less than average_ping_time of dest_ip3, after treatment it should be like:

[(ip2:ip2_ping_time),(ip1:ip1_ping_time),(ip3:ip3_ping_time)]

I have my Ansible task configured as:

- name: Create and add items to dictionary
    set_fact:
      all_hosts_average_ping_time: "{{ all_hosts_average_ping_time | default({}) | combine({item['ip'] : item['average_ping_time']}) }}"
    with_items:
    - { 'ip' : 'dest_ip1', 'average_ping_time' : 23.36  }
    - { 'ip' : 'dest_ip2', 'average_ping_time' : 24.79  }
    - { 'ip' : 'dest_ip3', 'average_ping_time' : 28.96  }

Upvotes: 2

Views: 3641

Answers (1)

Kevin C
Kevin C

Reputation: 5740

You can use the Jinja2 plugin called dictsort.

If you want to filter by the value:

# example values
# dest_ip1: 5.0
# dest_ip2: 1.0
# dest_ip3: 3.0

- debug:
    msg: "{{ all_hosts_average_ping_time | dictsort(false, 'value') }}"

Using my example values, this results in:

[
    "dest_ip2",
    1.0
],
[
    "dest_ip3",
    3.0
],
[
    "dest_ip1",
    5.0
]

If you want to reverse the order, simply add that statement to dictsort:

dictsort(false, 'value', reverse=true)

Upvotes: 2

Related Questions