为什么Python中for循环校验字典元素时仅检查首个条目
问题根因
- 逻辑分支绑定错误:你把输入不匹配的
else分支写在了for循环内部的if判断下,而非for循环遍历完全部key之后。
具体执行流程:你示例的字典第一个key是app_group2,如果用户输入的是Date,第一次循环时item取值为app_group2,和输入不匹配就会直接触发else分支:打印不存在提示 + 递归调用update_details()函数,当前循环直接终止,永远不会遍历到第二个keyDate。
修复方案
方案1:调整分支位置,保留for循环写法
把不存在的判定放到for循环全部执行完之后,利用Python的for...else语法(else分支只会在for循环没有被break中断时触发,也就是遍历完全部key都没匹配到的场景):
def update_details():# here the user choose which feild he want to update input_details = input("please select which field you want to change: ") for item in store_group_details: #check if feild exist in decionary if item == input_details: # removed ['type'] update_all_feature(input_details) # send input_details to update_all_feature() function break else: print ("your input dose not exist? ") update_details()
方案2:直接用字典原生成员判断,省略for循环(更简洁)
Python字典本身支持直接用in判断key是否存在,不需要手动遍历,完全避免循环逻辑错误:
def update_details():# here the user choose which feild he want to update input_details = input("please select which field you want to change: ") if input_details in store_group_details: update_all_feature(input_details) # send input_details to update_all_feature() function else: print ("your input dose not exist? ") update_details()
内容的提问来源于stack exchange,提问作者Mona Salih
相关产品推荐
相关产品推荐

