比较来自多个字典的值



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

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中搜索并返回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

如果您创建一个查找字典,将interfacesvrfs映射到name,那么您可以在单个列表推导中完成此操作。

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

相关内容

  • 没有找到相关文章

最新更新