Home > Mobile >  Compare values from multiple dictionaries
Compare values from multiple dictionaries

Time:05-10

I have two lists of dictionaries and a tuple:

vrfs = [
 {'default_rd': '<not set>',
  'interfaces': ['Gi0/0'],
  'name': 'Mgmt-vrf',
  'protocols': 'ipv4,ipv6'},
 {'default_rd': '12345:510',
  'interfaces': ['503', '510', '515'],
  'name': 'VLAN1',
  'protocols': 'ipv4,ipv6'},
 {'default_rd': '12345:993',
  'interfaces': ['993'],
  'name': 'VLAN2',
  'protocols': 'ipv4,ipv6'}
]

my_dict = [
 {'Device Name': '',
  'Hostname': 'switch1',
  'IP Address': '',
  'Interface Number': 'Gi1/0/2',
  'MAC': 'A0:B1:C2:D3:E4:F5',
  'VLAN': '503'},
 {'Device Name': '',
  'Hostname': 'switch1',
  'IP Address': '',
  'Interface Number': 'Gi1/0/3',
  'MAC': 'A1:B2:C3:D4:E5:F6',
  'VLAN': '510'},
 {'Device Name': '',
  'Hostname': 'switch1',
  'IP Address': '',
  'Interface Number': 'Gi1/0/4',
  'MAC': 'A2:B3:C4:D5:E6:F7',
  'VLAN': '515'},
 {'Device Name': '',
  'Hostname': 'switch1',
  'IP Address': '',
  'Interface Number': 'Gi1/0/5',
  'MAC': 'A3:B4:C5:D6:E7:F8',
  'VLAN': '993'},
 {'Device Name': '',
  'Hostname': 'switch1',
  'IP Address': '',
  'Interface Number': 'Gi1/0/6',
  'MAC': 'A4:B5:C6:D7:E8:F9',
  'VLAN': '750'}
]

vlans = ('Gi0/0', '503', '510', '515', '993')

And I need to iterate through my_dict but if my_dict["VLAN"] is in vlans tuple then I need search in vrfs and return the vrfs["name"].

So something like:

if vlan in vlans:
    print(f"show ip arp vrf {vrfs['name']} {my_dict}['MAC']")
else:
    print(f"show ip arp {my_dict}['MAC']")

How would I accomplish this?

CodePudding user response:

Your question is not clear but I do what I understand.

for a in my_dict:
    if a['VLAN'] in vlans:
        for i in vrfs:
            if a['VLAN'] in i['interfaces']:
                print(i['name'])

OUTPUT:

VLAN1
VLAN1
VLAN1
VLAN2

CodePudding user response:

If you make a lookup dict mapping interfaces to name from vrfs, then you can do this in a single list comprehension.

vrfs_lookup = {key: item['name'] for item in vrfs for key in item['interfaces']}

names = [vrfs_lookup[item['VLAN']] for item in my_dict if item['VLAN'] in vlans]

This will give you a list of names:

['VLAN1', 'VLAN1', 'VLAN1', 'VLAN2']
  • Related