如何将文本行转为指定键值对字典,为条目加唯一ID并存入列表?
问题描述
有一个文本文件,列名对应key_list中的字段:['vlan name', 'mac address', 'mac flags', 'age', 'logical interface', 'nh index', 'rtr id', 'IP'],文件内每行数据格式示例:
VLAN1100 84:03:28:a8:b3:18 D - ge-0/0/45.0 0 0 10.68.8.189:
已编写代码尝试将每行转为字典,但需要优化:
- 仅保留索引0、1、4、7对应的键值对(即
vlan name、mac address、logical interface、IP) - 为每个条目添加基于唯一
mac address的ID - 将所有字典存入列表以便后续查询
现有代码如下:
key_list = ['vlan name', 'mac address', 'mac flags', 'age', 'logical interface', 'nh index', 'rtr id', 'IP'] with open('prog-input.txt', 'r') as file: lines = file.readlines() #separate column data into lines for line in lines: if 'VLAN' in line: #skip headers entry = line.split() res = {} for key in key_list: for value in entry: res[key] = value entry.remove(value) break print(res) file.close()
实现方案
直接通过指定需要保留的索引与对应键的映射,同时利用mac地址的唯一性生成ID,最终将所有条目存入列表:
key_list = ['vlan name', 'mac address', 'mac flags', 'age', 'logical interface', 'nh index', 'rtr id', 'IP'] # 定义需要保留的索引和对应键的映射 target_fields = {0: 'vlan name', 1: 'mac address', 4: 'logical interface', 7: 'IP'} result_list = [] with open('prog-input.txt', 'r') as file: for line in file: line = line.strip() # 跳过空行和非数据行 if not line or 'VLAN' not in line: continue entry = line.split() # 清理IP字段末尾的冒号 if entry[7].endswith(':'): entry[7] = entry[7].rstrip(':') # 构建目标字典 item = {} for idx, key in target_fields.items(): item[key] = entry[idx] # 添加基于mac地址的唯一ID,直接用mac本身或哈希值均可 item['id'] = item['mac address'] # 若需要数字ID可替换为:item['id'] = hash(item['mac address']) result_list.append(item) # 验证输出 for entry in result_list: print(entry)
关键说明
- 精准筛选字段:通过
target_fields直接绑定需要的索引和键,避免无效遍历,提升效率 - 数据清洗:处理示例中IP字段末尾的多余冒号,保证数据准确性
- 唯一ID生成:利用mac地址本身的唯一性作为ID,也可通过
hash()转换为数字格式,按需选择 - 列表存储:所有条目存入
result_list,方便后续进行查询、过滤等操作
内容的提问来源于stack exchange,提问作者TurkishPoptart
相关产品推荐
相关产品推荐

