首页 > 解决方案 > 当这些在字典列表中时,如何通过不同的接口值有效地计算mac值的出现?

问题描述

换句话说,给定字典列表,我怎么能有效地得到一个接口列表,其中有多个 MAC 地址绑定到它们?在下面的示例中,我们将输出 Te1/1/1,因为该接口绑定了三个 mac 地址,结果可能包含多个接口。不应计算接口键的空白值。输入列表可能很长,所以我想知道解决这个问题的最快方法是什么?

{
   "mac_address_table": [
      {
         "active": true,
         "interface": "",
         "last_move": -1,
         "mac": "01:00:0C:CC:CC:CC",
         "moves": -1,
         "static": true,
         "vlan": 0
      },
      {
         "active": true,
         "interface": "",
         "last_move": -1,
         "mac": "01:00:0C:CC:CC:CD",
         "moves": -1,
         "static": true,
         "vlan": 0
      },
      {
         "active": true,
         "interface": "Gi1/0/3",
         "last_move": -1,
         "mac": "78:72:5D:2C:F7:B4",
         "moves": -1,
         "static": false,
         "vlan": 124
      },
      {
         "active": true,
         "interface": "Te1/1/1",
         "last_move": -1,
         "mac": "B0:90:7E:8E:EE:01",
         "moves": -1,
         "static": false,
         "vlan": 124
      },
      {
         "active": true,
         "interface": "Te1/1/1",
         "last_move": -1,
         "mac": "BC:26:C7:7F:B2:DD",
         "moves": -1,
         "static": false,
         "vlan": 124
      },
      {
         "active": true,
         "interface": "Te1/1/1",
         "last_move": -1,
         "mac": "BC:26:C7:7F:B2:DE",
         "moves": -1,
         "static": false,
         "vlan": 124
      }
   ]
}

标签: pythondictionary

解决方案


您可以使用 adefaultdict来跟踪特定接口名称被看到的次数。

然后你需要过滤掉只看到一次的接口。

interfaces = defaultdict(int)
for iface in data['mac_address_table']:
    if not iface['interface']:
        continue
    interfaces[iface['interface']] += 1

multi_mac_interfaces = [iface for iface, count in interfaces.items() if count > 1]
print(multi_mac_interfaces)

推荐阅读