Python中处理含重复键字典的最佳方法(花园浇水程序场景)
处理Python中含重复键的字典场景
在Python 3.6里处理这种重复键被覆盖的问题,结合你的花园浇水定时程序场景,我常用这几个实用方案:
方案一:使用collections.defaultdict(推荐)
defaultdict可以自动为不存在的键创建默认值(比如列表),完美解决重复键的存储问题,代码简洁可读性高:
from collections import defaultdict import time import configparser config = configparser.ConfigParser() config.read('your_config.ini') # 替换为你的配置文件路径 def getTimerFile(): """从文件获取定时任务并预处理。""" timerFile = config.get("Basic", "TimerFile") allowedDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] try: # 初始化一个默认值为列表的字典 schedule = defaultdict(list) with open(timerFile) as f: for line in f: line = line.rstrip() if not line: continue # 跳过空行避免报错 day, time_str = line.split(" ", 1) # 先校验星期是否合法 if day not in allowedDays: print(f"无效的星期: {day},已跳过") continue # 校验时间格式是否正确 try: time.strptime(time_str, "%H:%M") schedule[day].append(time_str) except ValueError: print(f"无效的时间格式: {time_str},已跳过") return schedule except FileNotFoundError: print(f"定时文件 {timerFile} 未找到") return defaultdict(list)
使用时,你可以通过schedule["Monday"]直接获取该星期所有的浇水时间列表,后续遍历处理定时任务非常方便。
方案二:手动处理普通字典(无需额外依赖)
如果不想导入collections模块,手动检查键是否存在再进行列表追加也是个稳妥的选择,适合小型程序场景:
import time import configparser config = configparser.ConfigParser() config.read('your_config.ini') def getTimerFile(): """从文件获取定时任务并预处理。""" timerFile = config.get("Basic", "TimerFile") allowedDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] try: schedule = {} with open(timerFile) as f: for line in f: line = line.rstrip() if not line: continue day, time_str = line.split(" ", 1) if day not in allowedDays: print(f"无效的星期: {day},已跳过") continue try: time.strptime(time_str, "%H:%M") # 检查键是否存在,存在则追加,不存在则创建列表 if day in schedule: schedule[day].append(time_str) else: schedule[day] = [time_str] except ValueError: print(f"无效的时间格式: {time_str},已跳过") return schedule except FileNotFoundError: print(f"定时文件 {timerFile} 未找到") return {}
方案总结
- 如果你追求代码简洁和可读性,**方案一的
defaultdict**是最佳选择,也是Python社区处理这类场景的常规做法; - 如果你希望避免额外模块依赖,方案二的手动处理足够满足你的小型浇水控制程序需求。
两种方案都能解决重复键被覆盖的问题,后续你可以根据返回的字典结构,轻松遍历每个星期对应的所有定时时间,实现浇水任务的调度。
内容的提问来源于stack exchange,提问作者DX667
相关产品推荐
相关产品推荐

