Jinja Selectattr: How to Filter a List of Dictionaries with Jinja

Jinja Selectattr: How to Filter a List of Dictionaries with Jinja

Jinja Tip!
Use selectattr to filter a list of dictionaries based on a matching condition.

# Input data
interfaces: 
  - { device: 'spine1', interface: 'GigabitEthernet0/0', ip: '10.1.1.1' }
  - { device: 'spine1', interface: 'GigabitEthernet0/1', ip: '10.1.2.1' }
  - { device: 'spine2', interface: 'GigabitEthernet0/0', ip: '10.2.1.1' }
  - { device: 'spine2', interface: 'GigabitEthernet0/1', ip: '10.2.2.1' }

# Jinja syntax
{{ interfaces | selectattr('device', 'equalto', "spine1") | list | pprint }}

# Result 
[{'device': 'spine1', 'interface': 'GigabitEthernet0/0', 'ip': '10.1.1.1'},
 {'device': 'spine1', 'interface': 'GigabitEthernet0/1', 'ip': '10.1.2.1'}]
Try it yourself

Subscribe to our newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox.
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!