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

Excel键值对读取与字典匹配校验:循环仅输出单行结果问题

问题描述

需要从Excel读取key-value数据,校验每一组数据是否存在于指定字典中。
Excel示例数据:

key       value
====      =====
v54      desktop
v7         nav
events    event6

当前运行代码后仅输出最后一行的校验结果:

Key-value pair found in dictionary events : event6

期望输出所有行的校验结果:

Key-value pair found in dictionary v54:desktop
Key-value pair found in dictionary v7:nav
Key-value pair found in dictionary events : event6

问题代码:

import colorama
from colorama import color, init
init()
import pandas as pd

# 假设已定义目标字典
dict = {"v54": "desktop", "v7": "nav", "events": "event6"}
df = pd.read_excel("your_input.xlsx")

for index in range (len(df)):
   key = df.loc[index,'key']
   value = df.loc[index,'value']

if key in dict and dict[key] == value:
    print("Key-value pair"" "+color.GREEN+"found"+color.END+ " ""in dictionary"" "+color.GREEN+ key +" : "+ value+color.END)
    df.at[index, 'result'] = 'PASS'
    
else:
    print("Key-value pair"" "+color.RED+ "not found"+color.END+" " "in dictionary"" "+color.RED+key +" : "+ value+color.END)
    df.at[index, 'result'] = 'FAIL'
        

# Save the updated dataframe to the Excel file
df.to_excel('test.xlsx', index=False)
解决方案

核心问题是缩进错误:if-else代码块没有被包含在for循环的范围内,导致循环结束后仅处理最后一次循环赋值的key和value。

修改方法:将if-else代码块缩进,使其属于for循环的内部代码,这样每一次循环都会执行校验和输出操作。

修改后的代码:

import colorama
from colorama import color, init
init()
import pandas as pd

# 目标字典(避免用dict作为变量名,覆盖Python内置类型)
target_dict = {"v54": "desktop", "v7": "nav", "events": "event6"}
df = pd.read_excel("your_input.xlsx")

for index in range(len(df)):
    key = df.loc[index, 'key']
    value = df.loc[index, 'value']
    
    # 缩进:将if-else放入循环内,逐行处理
    if key in target_dict and target_dict[key] == value:
        print(f"Key-value pair {color.GREEN}found{color.END} in dictionary {color.GREEN}{key} : {value}{color.END}")
        df.at[index, 'result'] = 'PASS'
    else:
        print(f"Key-value pair {color.RED}not found{color.END} in dictionary {color.RED}{key} : {value}{color.END}")
        df.at[index, 'result'] = 'FAIL'

# 保存更新后的Excel文件
df.to_excel('test.xlsx', index=False)

额外优化:用f-string简化字符串拼接,同时避免使用dict作为变量名(它是Python内置类型,会导致内置功能被覆盖)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:10:12