Python解析交换机配置的数据

时间:2015-12-13 16:31:35

标签: python list dictionary switching

我有这样的数据:

data = [{'1234': [{u'gateway_ip': u'172.20.21.1',
                u'ipv6_block': None,
                u'private_block': u'172.20.21.0/24',
                u'segment_name': u'VLAN1',
                u'switch_ports': [{u'name': u'fa0/32',
                                   u'switch_name': u'switch1.local',
                                   u'switch_port_interface_type_name': u'eth'},
                                  {u'name': u'fa0/15',
                                   u'switch_name': u'switch2.local',
                                   u'switch_port_interface_type_name': u'eth'}],
                u'vlan_name': u'INSIDE',
                u'vlan_number': 2031},
               {u'gateway_ip': u'172.20.31.1',
                u'ipv6_block': None,
                u'private_block': u'172.20.31.0/24',
                u'segment_name': u'VLAN2',
                u'switch_ports': [{u'name': u'fa0/32',
                                   u'switch_name': u'switch1.local',
                                   u'switch_port_interface_type_name': u'eth'},
                                  {u'name': u'fa0/15',
                                   u'switch_name': u'switch2.local',
                                   u'switch_port_interface_type_name': u'eth'}],
                u'vlan_name': u'DMZ',
                u'vlan_number': 2037}]}]

我想解析这些数据,得到这样的结果:

[{1234:[{switch1.local:[{fa0/32:[2031,2037],{fa0/15:[2031,2037]}}]},{switch2.local:[{fa0/32:[2031,2037],{fa0/15:[2031,2037]}}]}]}]

基本上我想得到分配给特定交换机端口和设备的vlan列表

[{device:[{switch1:{port1:[vlans-list]}},{switch1:{port2:[vlans-list]}}]}] 

当我这样做时,在列表中追加我现在知道的不正确我会得到这样的结果:

[{device:[{switch1:{port1:[vlan1]}},{device:[{switch1:{port2:[vlan2]}]}}]}]

我确信这对你来说没有任何意义,所以请提出问题我会尽力回答他们。

2 个答案:

答案 0 :(得分:0)

返回并不完全是您所建议的,但是,这样就会减少冗余数据。

dict_out = {'vlan_number': {}}

for i in data:
    for k, v in i.items():
        dict_out[k] = [{sp['switch_name']: sp['name'] for sp in i['switch_ports']}
                       for i in v]
        dict_out['vlan_number'][k] = [i['vlan_number'] for i in v]

返回:

{'vlan_number': {'1234': [2031, 2037]}, '1234': [{'switch1.local': 'fa0/32', 'switch2.local': 'fa0/15'}, {'switch1.local': 'fa0/32', 'switch2.local': 'fa0/15'}]}

答案 1 :(得分:0)

新代码,其他代码无法完全正常工作

<?php   
         foreach($result as $row){
            ?>
            <li><?php echo $row['first_name'].' '.$row['last_name'];?>
                <br/><strong>Email: </strong><?php echo $row['email'];?>
            </li>