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

Python中列表内字典的密码验证失败问题求助

密码验证失败的原因与修复方案

嘿,我来帮你梳理下问题所在:你当前的判断逻辑有个关键错误——user列表里存储的是字典对象,而不是单独的密码字符串。

当你执行if password in user:时,Python会检查输入的密码字符串是不是user列表里的直接元素。但你的user列表里每个元素都是包含User_Name、Password等键的字典,所以这个条件永远不会成立,自然一直显示登录失败。

修复方案

这里有两种简单的修复方式:

方式1:遍历用户列表逐一检查

password = input("Password: ")
is_logged_in = False
# 遍历每个用户字典,对比密码
for current_user in user:
    if current_user["Password"] == password:
        is_logged_in = True
        break

if is_logged_in:
    print("logged in")
else:
    print("log-in failed")

方式2:用any()函数简化判断

any()会遍历生成器表达式里的内容,只要有一个条件满足就返回True,代码更简洁:

password = input("Password: ")
if any(user_dict["Password"] == password for user_dict in user):
    print("logged in")
else:
    print("log-in failed")

额外优化建议

实际场景里只验证密码不太安全(比如多个用户可能设置相同密码),建议同时验证用户名+密码:

username = input("Username: ")
password = input("Password: ")
is_logged_in = False

for current_user in user:
    if current_user["User_Name"] == username and current_user["Password"] == password:
        is_logged_in = True
        break

if is_logged_in:
    print("logged in")
else:
    print("log-in failed")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 21:03:11