You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python解析CSV至字典时重复交换机键值更新问题

问题:Python解析CSV为字典时仅保留最后一条端口数据

原始代码

def create(excel_filename):
    ctr = 0
    #excel_filename = "Switch.csv"
    switchs = {}

    with open(excel_filename, "r") as excel_csv:
        for line in excel_csv:
            if ctr == 0:
                ctr+=1  # Skip the coumn header
            else:
                # save the csv as a dictionary
                switch,port,ibps,obps = line.replace(' ','').strip().split(',')
                if switch not in switchs:
                    switchs[switch] = {'port': [port], 'ibps': [ibps], 'obps': [obps]}
                else:
                    switchs[switch].update({'port': [port], 'ibps': [ibps], 'obps': [obps]})
    return switchs

s = create("machine1.csv")
print(s)

CSV文件内容(machine.csv)

switch,port,sent,received
switch1,ge-0/1,5800,5800
switch1,ge-0/2,1000,5700
switch2,ge-0/3,2000,3000
switch2,ge-0/4,3000,4000

期望输出

{'switch1': {'port': ['ge-0/1', 'ge-0/2'], 'sent': ['5800','1000'], 'received': ['5800','5700']}, 'switch2': {'port': ['ge-0/3','ge-0/4'], 'sent': ['2000','3000'], 'received': ['3000','4000']}}

问题分析

你的代码存在两个核心问题:

  • 使用update方法时,是直接用新的单元素列表替换掉交换机对应的原有列表,而非将新元素追加到列表中,导致之前的数据被覆盖,最终仅保留最后一条记录。
  • 变量名ibps、obps与CSV表头的sent、received不匹配,会导致字典键名和实际数据对应错误。

修改后的代码

def create(excel_filename):
    ctr = 0
    switchs = {}

    with open(excel_filename, "r") as excel_csv:
        for line in excel_csv:
            if ctr == 0:
                ctr += 1  # 跳过表头行
                continue
            # 处理行数据,去除空格并分割字段
            switch, port, sent, received = line.replace(' ', '').strip().split(',')
            if switch not in switchs:
                # 首次添加交换机时初始化列表
                switchs[switch] = {'port': [port], 'sent': [sent], 'received': [received]}
            else:
                # 向已有列表追加新元素,而非替换列表
                switchs[switch]['port'].append(port)
                switchs[switch]['sent'].append(sent)
                switchs[switch]['received'].append(received)
    return switchs

s = create("machine1.csv")
print(s)

更可靠的优化方案:使用内置csv模块

如果CSV字段中存在逗号或复杂格式,手动分割会出错,建议使用Python内置的csv模块处理,代码更健壮:

import csv

def create(excel_filename):
    switchs = {}

    with open(excel_filename, "r") as excel_csv:
        # 用DictReader直接按表头映射字段
        reader = csv.DictReader(excel_csv)
        for row in reader:
            # 去除字段前后可能存在的空格
            switch = row['switch'].strip()
            port = row['port'].strip()
            sent = row['sent'].strip()
            received = row['received'].strip()
            
            if switch not in switchs:
                switchs[switch] = {'port': [], 'sent': [], 'received': []}
            # 追加数据到对应列表
            switchs[switch]['port'].append(port)
            switchs[switch]['sent'].append(sent)
            switchs[switch]['received'].append(received)
    return switchs

s = create("machine1.csv")
print(s)

内容的提问来源于stack exchange,提问作者Juhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 13:54:22