Filtering a Dictionary Against a List of Values

Filtering a Dictionary Against a List of Values

Python Tip: You can filter a dictionary against keys that are present in a list by using dictionary comprehension.

Here’s an example 👇

vlans = {
    100: "VLAN-100-HR",
    200: "VLAN-200-IT",
    300: "VLAN-300-Finance",
}

filter_ids = [100, 300]

filtered_vlans = {
    vlan_id: vlan_name for vlan_id, vlan_name in vlans.items() if vlan_id in filter_ids
}

print(filtered_vlans)
# Output:
# {100: 'VLAN-100-HR', 300: 'VLAN-300-Finance'}

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!