Python使用for循环更新dict值 将Note Holder替换为对应家族名
问题描述
我通过两个列表创建了一个dict字典,目前需要更新字典内存储的值。我在for循环中使用if语句筛选出待修改的条目,需要修改这些条目对应的字典值:将值为字符串"Note Holder"的字典项,替换为对应家族名格式"The {Family Name} Family",也就是把字典中存储的"Note Holder"值更新为形如"The XX Family"的新名称。
原有实现代码
data = pd.read_excel('mailclean.xlsx') ran = range(len(data)) tes = list(data.iloc[0:len(data)]['Column1']) tes1 = list(data.iloc[0:len(data)]['Column2']) dic = {} for a in ran: dic[tes[a]] = tes1[a] for new_name in tes: if "Family Trust" in new_name: name = dic.get(new_name) new_name = "The " + new_name[:-6] print(new_name) print(name)
当前运行输出
The Guerland Family Note Holder The Sciammas Family Note Holder The Hsu Family Note Holder The Hemingway Family Note Holder The Williams Family Note Holder The Svancara Family Note Holder The Schritter Family Note Holder The Meola Family Note Holder The Scipione Family Note Holder The Elmore Family Note Holder The Oeland Family Note Holder The Harmsen Family Note Holder The Mauger Family Note Holder The Hockema Family Note Holder The Vogl Family Note Holder The McKee Family Note Holder The Davis Family Note Holder The Katz Family Note Holder The Grewal Family Note Holder The Penner Family Note Holder The Johnson Family Note Holder The Johnson Family Note Holder The Johnson Family Note Holder The Nemeth Family Note Holder The Horan Family Note Holder The Quan Family Note Holder The Elliott Family Note Holder The Clay Family Note Holder The Edwards Family Note Holder The Smith Family Note Holder The Rau Family Note Holder The Barter Family Note Holder The Lyon Family Note Holder The Scheiber Family Note Holder The Betzing Family Note Holder The Porter Family Note Holder The Eller Family Note Holder The Sebring Family Note Holder
问题原因
代码没有实际修改字典内容:
- 循环中仅拼接生成了新的家族名称字符串,没有执行字典赋值操作,字典本身的键值对从未被改动
- 变量命名混淆:遍历得到的
new_name实际是字典的键,后续直接覆盖该变量为新值,没有关联回字典的键值映射关系
修复后代码
import pandas as pd data = pd.read_excel('mailclean.xlsx') # 简化列读取逻辑,无需冗余切片 col1 = list(data['Column1']) col2 = list(data['Column2']) # 直接通过zip打包两个列表生成字典,无需手动计数循环 name_map = dict(zip(col1, col2)) # 遍历字典键值对完成更新 for key, value in name_map.items(): # 匹配需要修改的条目:键包含"Family Trust",且原值为"Note Holder" if "Family Trust" in key and value == "Note Holder": # 截去键末尾6个字符(即" Trust"),拼接成要求的家族名格式 new_family_name = f"The {key[:-6]}" # 执行字典赋值,完成值更新 name_map[key] = new_family_name # 可选打印校验结果 print(f"键:{key},新值:{new_family_name}")
说明
修复后所有符合条件的字典项都会被实际更新,后续直接使用name_map即可拿到修改后的值。原有代码中创建字典、读取Excel列的冗余写法也做了简化,执行效率更高。
内容的提问来源于stack exchange,提问作者Corey V
相关产品推荐
相关产品推荐

