Python中循环退出后字典内容丢失的问题求助
问题:Python多层循环填充字典后为空,触发foo()执行
在函数askduty_oncall中,多层循环内尝试为team_oncall_dict赋值,但退出循环后字典始终为空,导致后续if not team_oncall_dict判断执行foo()。需解决如何保留循环内的字典内容。
相关代码
def askduty_oncall(self, *args): session = APISession(PD_API_KEY, default_from=PD_USER_EMAIL) total = 1 # true or false limit = 40 teamteamnm = "Team Test Team" team_esp_name = "Team Test Escalation Policy" # 修正中文引号为英文 teamteamid = "" teamesplcyid = "" team_oncall_dict = {} if args: offset = args[0] total_teams = args[1] if offset <= total_teams: print("\nfunc with args with new offset {} called\n".format(offset)) teams = session.get('/teams?limit={0}&total={1}&offset={2}'.format(limit,total,offset)) else: print("Reached max teams, no more team records to pull") return else: print("\nFunc with no args called, hence pull first set of {} teams as defined by limit var\n".format(limit)) teams = session.get('/teams?limit={0}&total={1}'.format(limit,total)) if not teams.ok: return else: tj = teams.json() tjd = tj['teams'] for adict in tjd: if not adict['name'] == teamteamnm: continue elif adict['name'] == teamteamnm: teamteamid = adict['id'] print("\nFound team..\nFetched",adict['name'], "id: {0}".format(teamteamid)) print("Pull escalation policy for team '{}':'{}'".format(teamteamnm,teamteamid)) esclp = session.get('/escalation_policies?total={0}&team_ids%5B%5D={1}'.format(total,teamteamid)) if not esclp.ok: print("Pulling Escalation polices for team '{}' failed".format(teamteamnm)) return else: ep = esclp.json() epj = esclp.json()['escalation_policies'] if not epj: print("Escalation polices for team '{}' not defined".format(teamteamnm)) return else: for adict2 in epj: if not adict2['summary'] == team_esp_name: continue else: print("***************FOUND FOUND********************") teamesplcyid = adict2['id'] print("\nFetched {} id: {}\n".format(team_esp_name, teamesplcyid)) oncalls = session.get('/oncalls?total={0}&escalation_policy_ids%5B%5D={1}'.format(total,teamesplcyid)) if not oncalls.ok: print("issue with oncalls") # 修正中文引号为英文 return else: ocj = oncalls.json()['oncalls'] for adict3 in ocj: print("\n") print(adict3['escalation_level']) if i['escalation_level'] == 1: # 此处变量名错误 print(adict3['schedule']['summary'], adict3['user']['summary']) team_oncall_dict[adict3['schedule']['summary']] = adict3['user']['summary'] print(team_oncall_dict) return team_oncall_dict # 过早return if not team_oncall_dict: # 需确保缩进属于函数内部 foo()
执行输出
foo stuff
示例数据
[ {'escalation_policy': {'id': 'P8RKTEE', 'type': 'escalation_policy_reference', 'summary': 'Team Escalation Policy'}, 'escalation_level': 3, 'schedule': None, 'user': {'id': 'PX8XYFT', 'type': 'user_reference', 'summary': 'M1'}, 'start': None, 'end': None}, {'escalation_policy': {'id': 'P8RKTEE', 'type': 'escalation_policy_reference', 'summary': 'Team Escalation Policy'}, 'escalation_level': 1, 'schedule': None, 'user': {'id': 'PKXXVJI', 'type': 'user_reference', 'summary': 'R1'}, 'start': None, 'end': None}, {'escalation_policy': {'id': 'P8RKTEE', 'type': 'escalation_policy_reference', 'summary': 'Team'}, 'escalation_level': 2, 'schedule': None, 'user': {'id': 'PN8F9PC', 'type': 'user_reference','summary': 'T1'}, 'start': None, 'end': None} ]
问题分析与修复方案
1. 变量名错误导致赋值逻辑未触发
内层循环中使用未定义的变量i判断escalation_level,会直接抛出NameError,导致代码根本无法执行到字典赋值步骤。需将i替换为当前循环变量adict3。
2. 过早的return终止函数
在字典赋值后立即执行return team_oncall_dict,会直接终止函数,且该return缩进在if判断内部,导致仅找到第一个符合条件的条目就退出,后续循环无法执行。若函数为递归调用,返回值未被外层正确接收时,team_oncall_dict仍为空。需移除该过早的return,或调整到所有循环完成后统一返回。
3. 空指针风险导致赋值失败
示例数据中schedule字段为None,直接访问adict3['schedule']['summary']会抛出AttributeError,需先判断schedule不为None再赋值。
4. 语法错误(中文引号)
代码中多处使用中文引号(如team_esp_name = “Team Test Escalation Policy"),属于语法错误,需替换为英文引号。
5. 缩进错误导致判断逻辑失效
末尾的if not team_oncall_dict缩进错误,需确保其属于函数内部的代码块,否则无法正确判断字典状态。
修复后的关键代码片段
# 内层循环部分修改 for adict3 in ocj: print("\n") print(adict3['escalation_level']) # 修正变量名+空值判断 if adict3['escalation_level'] == 1 and adict3['schedule'] is not None: print(adict3['schedule']['summary'], adict3['user']['summary']) team_oncall_dict[adict3['schedule']['summary']] = adict3['user']['summary'] print(team_oncall_dict) # 移除过早的return,在函数末尾统一处理返回或判断 if not team_oncall_dict: foo() # 可选:若需要返回字典,在函数末尾添加 # return team_oncall_dict
内容的提问来源于stack exchange,提问作者AhmFM
相关产品推荐
相关产品推荐

