比较来自多个字典的值

Compare values from multiple dictionaries

我有两个字典列表和一个元组:

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')

我需要遍历 my_dict 但如果 my_dict["VLAN"]vlans 元组中,那么我需要在 vrfs 和 return 中搜索 vrfs["name"].

所以像这样:

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

我该如何完成?

你的问题不清楚,我按照我的理解去做。

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

输出:

VLAN1
VLAN1
VLAN1
VLAN2

如果您从 vrfs 进行查找字典映射 interfacesname,那么您可以在单个列表理解中执行此操作。

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]

这会给你一个名字列表:

['VLAN1', 'VLAN1', 'VLAN1', 'VLAN2']